3

找到带有解决方案的帖子如何处理失败的 DllImport?

我正在编写一个应用程序来检查操作系统版本以根据主机是使用 Vista 系列还是 NT 系列版本的 Windows 来执行不同的操作。如果是 Vista 系列,它会加载一些 DLL(使用 DllImport),但不使用这些。问题是,如果在没有这些 DLL 的旧版本 Windows 上使用,使用 DllImport 加载它们将在运行时导致 DllNotFoundException。

如何捕获/防止/忽略 DllNotFoundExceptions?尝试在我的未处理异常事件中将异常设置为“已处理”不允许应用程序继续。

4

2 回答 2

2

我认为您应该能够使用 win32 LoadLibrary/GetProcAddress/FreeLibrary 和委托(就像使用回调函数一样)采用“传统”方式。

http://msdn.microsoft.com/en-us/library/d186xcf0.aspx可能是一个起点......

这应该让你开始:

[DllImport("kernel32.dll", SetLastError=true)]
public static extern IntPtr LoadLibrary(string lpFileName);

[DllImport("kernel32.dll", SetLastError=true)]
static extern bool FreeLibrary(IntPtr hModule);

[DllImport("kernel32.dll", CharSet=CharSet.Ansi, ExactSpelling=true, SetLastError=true)]
public static extern IntPtr GetProcAddress(IntPtr hModule, string procName);

然后,您使用要调用的导出的正确签名声明一个委托,并使用 Marshal.GetDelegateForFunctionPointer()从您从GetProcAddress返回的函数指针创建它。

于 2009-11-06T10:35:04.560 回答
1

作为一种选择,您可以在 C++/CLI 中编写某种装饰器组件,该组件将使用 LoadLibrary 或静态链接将所有调用转发到 Windows dll,并手动处理这些 dll 的任何缺失。

于 2009-11-06T10:34:02.697 回答