基于64位或32位操作系统导入外部DLL

Mik*_*e_G 8 .net c# windows winforms

我有一个32位和64位版本的dll.我的.NET WinForm配置为"任何CPU",我的老板不会让我们为不同的操作系统版本单独安装.所以我想知道:如果我在安装中打包两个dll,那么有没有办法让WinForm确定它的64位/ 32位并加载正确的dll.

我发现这篇文章用于确定版本.但我不知道如何注入正确的方法来定义我想要使用的方法的DLLImport属性.有任何想法吗?

Han*_*ant 14

您可以利用SetDllDirectory API函数,它会改变非托管程序集的搜索路径.将32位DLL存储在app安装目录的x86子目录中,即x64子目录中的64位DLL.

在进行任何P/Invoke之前,在app启动时运行此代码:

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);
Run Code Online (Sandbox Code Playgroud)


Kie*_*ron 6

你可以导入它们并决定通过.NET调用哪一个?

例如:

[DllImport("32bit.dll", CharSet = CharSet.Unicode, EntryPoint="CallMe")]
public static extern int CallMe32 (IntPtr hWnd, String text, String caption, uint type);

[DllImport("64bit.dll", CharSet = CharSet.Unicode, EntryPoint="CallMe")]
public static extern int CallMe64 (IntPtr hWnd, String text, String caption, uint type);
Run Code Online (Sandbox Code Playgroud)