简体   繁体   中英

LoadLibrary() relative address to dll

I am trying to load a dll in my code in windows, I load my dll successfully with LoadLibrary() function but I have a question, I give the path to my dll like:

LoadLibrary(C:\\path\\to\\my\\dll);

I wonder if I can give the relative path to my dll. I mean for example:

LoadLibrary(.\my dll directory\my dll.dll)

Is it possible? if not, how can I develop my project which it can be portable without changing the path to dll in different machines?

It's most likely failing because you forgot to escape the backslashes in your second call to LoadLibrary. Maybe that was a typo when wrote your question, because you also forgot the quote marks for the file name. ;) That is, change this line:

LoadLibrary(.\my dll directory\my dll.dll);

To be this:

LoadLibrary(L".\\my dll directory\\my dll.dll");

(And I'm not sure if the leading .\\\\ is needed)

And if that doesn't fix it, then this most likely will do what you need:

wchar_t szFullPath[MAX_PATH] = {};
GetCurrentDirectory(MAX_PATH, szFullPath);
PathCchAppend(szFullPath, MAX_PATH, L"my dll directory\\my dll.dll");
HMODULE hDLL = LoadLibrary(szFullPath);

And finally, LoadLibrary has different behaviors for searching for dependent DLLs. And it varies based on how you specify the path. That might be what's impacting your ability to load the DLL from a relative search path. Read the MSDN page on it and consider looking at the various options calls such as LoadLibraryEx and SetDllDirectory can do for making search paths easier to deal with. This page on DLL search paths as well.

First of all, I assume that you meant to write:

LoadLibrary(".\\my dll directory\\my dll.dll");

The documentation answers your question:

If a relative path is specified, the entire relative path is appended to every token in the DLL search path list. To load a module from a relative path without searching any other path, use GetFullPathName to get a nonrelative path and call LoadLibrary with the nonrelative path.

So yes, you can specify a relative path. But the way it is interpreted is perhaps not what you were expecting. The DLL search will take each path in the DLL search path in turn, combine that with your relative path, and try to load that DLL.

So, if you want your relative path to be relative to the current working directory, call GetFullPathName to expand it to an absolute path, and then load that. If you want your relative path to be interpreted relative to some other directory, then combine with that directory and load the DLL with an absolute path.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM