VC++ 中LoadLibrary的路径问题

来源:互联网 发布:阿儿法营编程学校 编辑:程序博客网 时间:2024/06/05 15:16

已有动态库A.dll, 创建动态库B.dll和C.exe

在B.dll中编写:LoadLibrary("A.dll")

在C.exe中编写:LoadLibrary("B.dll")

把A.dll和B.dll放到C.exe相同的目录,运行C.exe正常。


把A.dll和B.dll放到文件夹DLL中,在C.exe 中改为LoadLibrary(“DLL\B.dll”),运行失败。


原因在于LoadLibrary搜索dll的顺序为:

    The directory from which the application loaded. (应用程序所在的目录) 
    The system directory. Use the GetSystemDirectory function to get the path of this directory. (system32目录)
    The 16-bit system directory. There is no function that obtains the path of this directory, but it is searched. (System目录) 
    The Windows directory. Use the GetWindowsDirectory function to get the path of this directory. (Windows目录) 
    The current directory. (不清楚这个目录和应用程序所在的目录有什么区别) 
    The directories that are listed in the PATH environment variable. Note that this does not include     the per-application path specified by the App Paths registry key. (PATH 路径) 

加载B.dll时,在exe所在目录能够查找到“DLL\B.dll”,所以能够加载到B.dll,但是加载A.dll时,在所有目录中都找不到"A.dll",所以加载失败。 在B.dll中写成“A.dll”的目的就是使用A相对于B的相对路径来加载A.dll, 但是LoadLibrary并没有使用到B的路径。

解决方法:使用SetDllDirectory增加DLL搜索路径,
HMODULE hMod = GetModuleHandle(("B.dll"));
if (hMod != NULL)
{
TCHAR szBuffer[MAX_PATH] = { 0 };
GetModuleFileName(hMod, szBuffer, sizeof(szBuffer) / sizeof(TCHAR) - 1);

string str;
str.append(szBuffer);
size_t pos=str.find_last_of("\\");
str.erase(pos);


SetDllDirectory(str.c_str());
   LoadLibrary("A.dll")
SetDllDirectory
(null);

}

阅读全文
0 0
原创粉丝点击