问题
I'm new to the "hidden/dark places" of C++ and I was wondering how to load a .dll file from a different directory or a sub-directory inside the one where my current executable is running
Ex:
./MyAppDirectory
/MyApp.exe
/SomeDLL.dll
/AnotherDLL.dll
/SubDirectory
/SomeDLL2.dll
/AnotherDLL2.dll
/YetAnotherDLL.dll
/...
So "MyApp.exe" automatically loads "SomeDLL.dll" and "AnotherDLL.dll" from it's root folder "MyAppDirectory" however I also want to be able to load "SomeDLL2.dll", "AnotherDLL2.dll", "YetAnotherDLL.dll" etc. from the "SubDirectory" folder inside the "MyAppDirectory" folder.
I've been doing some searches and from what I've found the only solutions are:
- 1) Modify the working directory of the executable.
- 2) Put the DLL files inside the Windows root.
- 3) Modify the PATH environment variable.
But all of them have some bad sides (not worth mentioning here) and it's not what I actually need. Also another solution is through "Application Specific Paths!" which involves working with Windows registry and seems the be slightly better then the ones mentioned before.
However I need to be able to do this inside "MyApp.exe" using C++ without the need to use external methods.
I'm using MinGW 4.7.2 and my IDE is Code::Blocks 12.11 also my OS is Windows XP SP3 Pro x86.
Any reference, tutorial, documentation, example etc. is accepted and thank you for your time :D
回答1:
If you are NOT explicitly loading the DLL ("manually", in your code using LoadLibrary(...)
), then you HAVE to have the .dll in a place that Windows will look for DLL's, whihc pretty much means one of the three options you are talking about in your question.
When using LoadLibrary
, you can specify a relative or absolute path to the DLL.
Note that it's completely different to load DLL's explicitly and implicitly - in the explicit case, you have to use the LoadLibrary
, and then use GetProcAddress
to find the address of the function, and you will have to use function pointers to call the functions - this is typically only used for plug-ins or similar functionality where the DLL provides a small number of functions (quite often just a factory function to create a objects to do something that has a generic interface class, and each DLL has the same type of function to create an object to do whatever it is supposed to do).
In the implicit load, you don't need to do anything in your code to use the DLL, and the functions from the DLL just appear to be there as if they were hard-linked into the application.
回答2:
You should use
LoadLibrary("subFolder\\dynamicLibrary.dll");
That's the explicit link to DLLs, it's a bit tougher than the implicit linking(that I think it's what you are using), but I believe that this is the correct way to achieve your purpose
explicit
implicit
来源:https://stackoverflow.com/questions/17420455/c-load-dll-from-a-subdirectory