针对32位或64位原生的DLL根据环境而定

编程入门 行业动态 更新时间:2024-10-13 02:13:44
本文介绍了针对32位或64位原生的DLL根据环境而定的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一个原生的DLL它来在32位和64位版本(86)。我想创建一个包装适用于这两种体系结构(任何CPU)和加载正确的版本根据当前环境的DLL(32位或64位,在运行时!)。这个过程应该自动发生,让自己的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 事件加载正确版本的一个可能的解决方案。然而,这需要我在另外3托管程序到2非托管库,这似乎有点矫枉过正。

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
  • 在船上一切都在相同的路径
  • name the 32-bit assembly with a "32-bit oriented name". For example MyAssembly.Native.x86.dll
  • name the 64-bit assembly with a "64-bit oriented name". For example MyAssembly.Native.x64.dll
  • compile the managed assembly as 'Any Cpu'
  • ship everything in the same path

下面是我如何申报的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 /调用的:

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加载路径

的不便之处是:

  • 您将有3个方法声明为1'真正'的方法
  • 您会宽松一些,因为CPU的位数测试周期
  • 根据你的情况下,有时你不能改变本机的DLL名称,这样你就不能做到这一点

更多推荐

针对32位或64位原生的DLL根据环境而定

本文发布于:2023-11-05 18:31:07,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1561550.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:而定   环境   DLL

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!