我有一些代码试图加载一个Dll。
我在这方面遇到了一个奇怪的‘错误’。当试图从绝对路径加载dll时,我得到一个非空HMODULE,它在GetLastError调用上不提供窗口错误代码(即,GetLastError根据msdn返回'0‘或成功)。在此dll中调用函数时,我会得到不正确的值。
这种行为是特殊的,因为如果我使用SetCurrentDirectory将当前目录切换为当前dll的目录,并使用对LoadLibrary的相对路径调用,则会得到正确的值。
下面是一个描述情况的片段:
使用绝对路径:
std::string libLoc = get_dll_location(); // Get the directory of this dll
HMODULE myDLL = LoadLibraryA(libLoc.c_str()); // Non-null value
DWORD lastError = GetLastError(); // returns 0
MyObj * value = UseDLL(myDLL); // bad value
使用相对路径:
SetCurrentDirectory("c:\\path\\containing\\dll\\"); // hard coded path to dll's folder
HMODULE myDLL = LoadLibrary("myDll.dll"); // Non-null value
MyObj * value = UseDLL(myDLL); // Good value
我真的很想避免使用SetCurrentDirectory,因为使用这个Dll的应用程序可能是多线程的,并且要求目录保持不变。
如果对此问题有任何见解,将不胜感激。希望这只是我的一个小问题。
Update:使用LoadLibraryEx似乎是不可能的,因为LOAD_LIBRARY_SEARCH_*标志似乎对我来说是不可用的(我已经尝试过安装KB2533623更新)。
发布于 2012-11-06 17:34:09
尝试设置SetDllDirectory或AddDllDirectory而不是SetCurrentDirectory,并使用LoadLibraryEx和标志LOAD_LIBRARY_SEARCH_USER_DIRS而不是LoadLibrary。可以在MSDN 这里上找到有用的信息。
更新:Windows7上的AddDllDirectory和相关调用示例(需要KB2533623)
#include "stdafx.h"
#include <iostream>
#include <Windows.h>
typedef DLL_DIRECTORY_COOKIE (WINAPI *ADD_DLL_PROC)(PCWSTR);
typedef BOOL (WINAPI *REMOVE_DLL_PROC)(DLL_DIRECTORY_COOKIE);
#ifndef LOAD_LIBRARY_SEARCH_USER_DIRS
#define LOAD_LIBRARY_SEARCH_USER_DIRS 0x00000400
#endif
int main()
{
ADD_DLL_PROC lpfnAdllDllDirectory = (ADD_DLL_PROC)GetProcAddress(GetModuleHandle(TEXT("kernel32.dll")), "AddDllDirectory");
REMOVE_DLL_PROC lpfnRemoveDllDirectory = (REMOVE_DLL_PROC)GetProcAddress(GetModuleHandle(TEXT("kernel32.dll")), "RemoveDllDirectory");
if(lpfnAdllDllDirectory && lpfnRemoveDllDirectory)
{
DLL_DIRECTORY_COOKIE cookie = ((ADD_DLL_PROC)lpfnAdllDllDirectory)(L"c:\\windows\\system32\\");
std::cout << cookie << std::endl;
HMODULE module = LoadLibraryEx(L"cabview.dll", NULL, LOAD_LIBRARY_SEARCH_USER_DIRS);
if(module)
{
std::cout << "Locked and loaded" << std::endl;
FreeLibrary(module);
}
if(cookie && ((REMOVE_DLL_PROC)(cookie)))
{
std::cout << "Added and removed cookie" << std::endl;
}
}
std::cin.get();
return 0;
}
https://stackoverflow.com/questions/13255845
复制相似问题