C#:根据平台访问 32 位/64 位 DLL [英] C#: Access 32-bit/64-bit DLL depending on platform

查看:54
本文介绍了C#:根据平台访问 32 位/64 位 DLL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们使用来自 C# 应用程序的自行编写的 32 位 C++ DLL.现在我们注意到,当C#应用程序在64位系统上运行时,会自动使用64位运行时,当然64位运行时无法访问32位DLL.

we use a self-written 32bit C++ DLL from our C# applications. Now we've noticed that when the C# applications are run on a 64bit system, the 64bit runtime is automatically used and of course the 32bit DLL can not be accessed from the 64bit runtime.

我的问题是:有没有办法使用 32 位 DLL?如果没有,如果我创建了 64 位版本的 DLL,是否可以轻松地让应用程序选择 P/Invoke 到哪个?

My question is: is there a way of using the 32bit DLL? If not, if I created a 64bit version of the DLL, would it be easily possible to let the application choose which one to P/Invoke to?

我正在考虑在 C# 中创建两个帮助程序类:一个从 32 位 DLL 导入函数,一个从 64 位 DLL 导入,然后为每个导入的函数创建一个包装类,其中调用 32 位导入器或 64 位导入器,具体取决于操作系统的比特性".那行得通吗?

I'm thinking of creating two helper classes in C#: One that imports the functions from the 32bit DLL and one that imports from the 64bit DLL, then creating a wrapper class with one function for each imported function that calls either the 32bit importer or the 64bit importer depending on the "bittyness" of the OS. Would that work?

或者有其他简单的方法吗?

Or is there another easy way to do things?

推荐答案

在 64 位编译时,您需要确保仅对 64 位 DLL 使用 P/Invoke 调用.

You need to make sure that you're only using P/Invoke calls against a 64bit DLL when compiling in 64bit.

一种选择是将所有方法"移动到标准接口(或抽象基类)中,并提供两种实现,一种是 32 位,一种是 64 位.您可以让工厂方法根据 IntPtr 的大小构造适当的类实例.

One option is to move all of your "methods" into a standard interface (or abstract base class), and provide 2 implementations, one 32bit and one 64bit. You can have a factory method construct the appropriate instance of the class depending on the size of IntPtr.

这允许AnyCPU"应用程序在运行时正确地确定 P/Invoke 到哪个 DLL 中,并且确实可以工作.

This allows an "AnyCPU" app to correctly, at runtime, determine which DLL to P/Invoke into, and does work.

这篇关于C#:根据平台访问 32 位/64 位 DLL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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