VC++ 中LoadLibrary的路径问题

已有动态库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);

}

  • 4
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值