【发布时间】:2015-08-06 05:47:06
【问题描述】:
我正在尝试使用 LoadLibraryEx 在 C# 中加载 win32 dll。
它不工作 - 我在 Visual Studio 中收到一条消息“vshost32.exe 已停止工作”。没有例外或任何关于它为什么不起作用的线索。
我不认为这是一个依赖问题,因为如果我更改依赖项的搜索路径,我会收到一个消息框,指出“找不到 xyz.dll”。
我想知道是否有办法找出它无法正确加载的原因。程序停止运行就行了:
IntPtr pDll = LoadLibraryEx(@"C:\Program Files\XXX\XXX.dll", IntPtr.Zero, flags);
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
private delegate void ImportResults();
[DllImport("kernel32.dll", SetLastError = true)]
public static extern IntPtr LoadLibraryEx(string dllToLoad, IntPtr hFile, LoadLibraryFlags flags);
[DllImport("kernel32.dll", SetLastError = true)]
public static extern IntPtr GetProcAddress(IntPtr hModule, string procedureName);
[DllImport("kernel32.dll", SetLastError = true)]
public static extern bool FreeLibrary(IntPtr hModule);
[System.Flags]
public enum LoadLibraryFlags : uint
{
DONT_RESOLVE_DLL_REFERENCES = 0x00000001,
LOAD_IGNORE_CODE_AUTHZ_LEVEL = 0x00000010,
LOAD_LIBRARY_AS_DATAFILE = 0x00000002,
LOAD_LIBRARY_AS_DATAFILE_EXCLUSIVE = 0x00000040,
LOAD_LIBRARY_AS_IMAGE_RESOURCE = 0x00000020,
LOAD_WITH_ALTERED_SEARCH_PATH = 0x00000008,
LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR = 0x00000100,
LOAD_LIBRARY_SEARCH_SYSTEM32 = 0x00000800,
LOAD_LIBRARY_SEARCH_DEFAULT_DIRS = 0x00001000
}
public void Import()
{
LoadLibraryFlags flags = LoadLibraryFlags.LOAD_LIBRARY_SEARCH_DEFAULT_DIRS |
LoadLibraryFlags.LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR;
IntPtr pDll = LoadLibraryEx(@"C:\Program Files\XXX\XXX.dll", IntPtr.Zero, flags);
IntPtr pAddressOfFunctionToCall = GetProcAddress(pDll, "ImportResults");
ImportResults import = (ImportResults)Marshal.GetDelegateForFunctionPointer(pAddressOfFunctionToCall,
typeof(ImportResults));
import();
bool result = FreeLibrary(pDll);
}
更新:
我已经下载了 windows sdk 并尝试使用 cdb.exe 使用此处描述的过程来调试问题:http://blogs.msdn.com/b/junfeng/archive/2006/11/20/debugging-loadlibrary-failures.aspx
运行该实用程序时,我使用的是这个命令行:
"C:\Program Files (x86)\Windows Kits\8.1\Debuggers\x86\cdb.exe" loadlib "C:\Program Files\XXX\XXX\XXX.DLL"
该文件肯定存在,所以我不确定我在这里做错了什么。
【问题讨论】:
-
在 VS 中启用非托管代码调试和从 VS 调试
-
可能您的 dll 已找到,但它需要一个或多个不同的 dll 以某种方式丢失。您的 dll 是否需要其他 dll(即静态链接到可能不在同一路径中的其他 dll?)
标签: c# pinvoke loadlibrary