c# - 基于64位或32位操作系统导入外部dll

标签 c# .net windows winforms

我有一个 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/

相关文章:

c# - 以编程方式提升进程特权?

c# - 从 C# Windows 窗体调用 PHP Web 服务

c# - Google OAuth2.0 中的 ProcessUserAuthorization 抛出 400 错误

.net - 构造函数中的事件处理程序 - 可能还是明智?

c# - 缓存 == 空?是否可以?

javascript - 如何将 Angular JavaScript 代码转换为原生 Windows 应用程序?

windows - 如何在 Visual Studio C++ 项目中指定 "any Windows SDK version greater than 10.0"?

c# - 如何以编程方式将内容类型添加到索引?

c# - 在 C# 中为 AWS REST 查询创建 HMAC 签名

c# - 如何在一段时间后停止异步任务