I have a DLL which is written in native C++. The Visual Studio project name is MyDll
and it compiles to a file called MyDll.dll
in the output directory.
After compilation, I rename it to MyDll2.dll
. (This example seems silly but I have a good reason for renaming it.)
A second project, written in C++/CLI, uses this DLL.
At compile time, this project references MyDll.lib
(generated when MyDll is compiled) to be able to use classes defined in the dll.
At runtime, to load the DLL, I call LoadLibrary, passing it the full path of the file C:\...\MyDll2.dll
(it's actually in the same folder). It loads successfully, as shown by LoadLibrary's return value.
At the first occurence in code where I use a class defined in the DLL (just declaring an object on the stack), it crashes with an SEHException
(these exceptions give no information whatsoever about the cause of the crash...)
This only hap开发者_开发技巧pens if I do the renaming step. If I leave it as MyDll.dll
and call LoadLibrary on that file, everything works fine. So it is obviously due to the renaming.
Any ideas why? Am I not allowed to rename the DLL?
(EDIT: clarifying by giving more details)
When building a dll the linker also generates a lib-file which you use to link with in your executable. This lib file contains the dll-name from which the exported functions and data are being imported. So your executable has references to originally name dll in it.
Why are you renaming a DLL after it's been loaded? You should never rename a DLL after you called LoadLibrary. I'm surprised the OS would even allow you to do that.
in which case I would have to recompile to change the file name
Yes you do, the LoadLibrary() argument must be changed when you rename the DLL. Fix your real problem, it doesn't sound like you check the return value of LoadLibrary() at all. Throw a Win32Exception when it returns NULL.
I agree with Edwin. The lib file directions to exported functions and also contains the name of dll which was at compile time.
I don't know if anyone will be reading this after a year, but why was OP even LoadLibrary'ing this renamed dll when it was already statically linked? This is 2 different things. I think OP's app was crashing due to lack of MyLib.dll, required after static linkage, and LoadLibrary has nothing to do with it, OP could as well omit LoadLibrary of MyLib2.dll and the result would be exactly the same. Only thing i can't explain is unknown error mentioned.
精彩评论