目标 32 位或 64 位本机 DLL,具体取决于环境 [英] Target 32 Bit or 64 Bit native DLL depending on environment

查看:19
本文介绍了目标 32 位或 64 位本机 DLL,具体取决于环境的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 32 位和 64 位版本 (x86) 的本机 DLL.我想创建一个适用于两种架构(任何 CPU)的包装器,并根据当前环境(32 位或 64 位,在运行时!)加载正确版本的 DLL.这个过程应该自动发生,所以我的 DLL 的用户不需要针对特定​​的体系结构.

I have a native DLL which comes in both 32 bit and 64 bit versions (x86). I want to create a wrapper which works on both architectures (Any CPU) and loads the correct version of the DLL depending on the current environment (32 Bit or 64 Bit, at runtime!). This process should happen automatically, so that the users of my DLL do not need to target a specific architecture.

是否有关于如何做到这一点的最佳实践?任何可以指导我的示例?

Are there any best practices on how to do that? Any examples that could guide me?

我找到了一种可能的解决方案,它为每个架构使用托管代理,然后使用 Assembly.Resolve 事件加载正确的版本.然而,这需要我除了 2 个非托管库之外还有 3 个托管程序集,这似乎有点过头了.

I found one possible solution that uses managed proxies for each architecture and then uses the Assembly.Resolve event to load the correct version. However this requires me to have 3 managed assemblies in addition to the 2 unmanaged libraries, which seems a bit overkill.

还有其他解决办法吗?

推荐答案

以下是我在许多项目中使用的解决方案:

Here is the solution I've used on many projects:

  • 使用面向 32 位的名称"命名 32 位程序集.为了示例 MyAssembly.Native.x86.dll
  • 使用面向 64 位的名称"命名 64 位程序集.例如 MyAssembly.Native.x64.dll
  • 将托管程序集编译为任何 Cpu"
  • 以相同的路径运送所有内容

以下是我声明 P/Invoke 方法的方式:

Here is how I declare P/Invoke methods:

[DllImport("MyAssembly.Native.x86.dll", EntryPoint = "MyTest")]
private static extern void MyTest86(MyType myArg);

[DllImport("MyAssembly.Native.x64.dll", EntryPoint = "MyTest")]
private static extern void MyTest64(MyType myArg);

这里是相应的MyTest"函数,我将一直使用它(其他函数只是为了正确的位绑定).它具有与其他 P/Invoke 相同的签名:

And here is the corresponding 'MyTest' function which is the one I'll always use (the others are here just for correct bitness binding). It has the same signature than the other P/Invoke ones:

public static void MyTest(MyType myArg)
{
    if (IntPtr.Size == 8)
    {
        MyTest64(myArg);
        return;
    }

    MyTest86(myArg);
}

优点是:

  • 您可以在同一路径中传送所有二进制文件(DLL、EXE、...)
  • 您支持具有相同文件布局的 32 位和 64 位进程和操作系统
  • 您不必求助于 Win32 api 来更改 dll 加载路径

不便之处在于:

  • 对于 1 个真实"方法,您将有 3 个方法声明
  • 由于位数测试,您会丢失一些 CPU 周期
  • 根据您的上下文,有时您无法更改本机 DLL 名称,因此您不能这样做

这篇关于目标 32 位或 64 位本机 DLL,具体取决于环境的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆