我有一个 32 位和 64 位版本的 dll。我的 .NET WinForm 配置为“任何 CPU”,我的老板不会让我们为不同的操作系统版本单独安装。所以我想知道:如果我在安装中打包两个 dll,那么有没有办法让 WinForm 确定它是 64 位/32 位并加载正确的 dll。
我找到了 this article用于确定版本。但我不确定如何注入(inject)正确的 在我希望使用的方法上定义 DLLImport 属性的方法。有什么想法吗?
最佳答案
您可以利用 SetDllDirectory API 函数,它会更改非托管程序集的搜索路径。将 32 位 DLL 存储在应用安装目录的 x86 子目录中,将 64 位 DLL 存储在 x64 子目录中。
在执行任何 P/Invoke 之前,在应用程序启动时运行此代码:
using System.IO;
using System.Reflection;
using System.Runtime.InteropServices;
...
public static void SetUnmanagedDllDirectory() {
string path = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location);
path = Path.Combine(path, IntPtr.Size == 8 ? "x64 " : "x86");
if (!SetDllDirectory(path)) throw new System.ComponentModel.Win32Exception();
}
[DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
private static extern bool SetDllDirectory(string path);
关于c# - 基于64位或32位操作系统导入外部dll,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2593916/