使用托管代码包装器从 64 位托管代码调用 32 位非托管代码的最佳方法 [英] Best way to call 32-bit unmanaged code from 64-bit Managed Code using a managed code wrapper

查看:35
本文介绍了使用托管代码包装器从 64 位托管代码调用 32 位非托管代码的最佳方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

随着 64 位机器和应用程序的流行,我遇到必须从托管 64 位进程调用本机 32 位代码的情况的频率正在增加.我不想将我的应用程序标记为 32 位,而且我无法获得正在调用的代码的 64 位版本.

The frequency with which I am coming across the situation where I have to call native 32-bit code from a managed 64-bit process is increasing as 64-bit machines and applications become prevalent. I don't want to mark my applciation as 32-bit and I cannot obtain 64-bit versions of of the code that is being calling.

我目前使用的解决方案是创建在进程外加载的 C++ COM 垫片,以便从 64 位进程进行 32 位调用.

The solution that I currently use is to create C++ COM shims that are loaded out of process to make the 32-bit calls from the 64-bit process.

这个 COM shim 解决方案运行良好,跨进程调用由 COM 在后台处理,最大限度地减少了这种方法的开销.

This COM shim solution works well and the cross process calls are handled behind the scenes by COM, which minimises the overhead of this approach.

然而,我想保留我们使用 C# 进行的所有新开发,并想知道是否有任何框架可以最大限度地减少这样做的开销.我看过 IPCChannel,但我觉得这种方法不如 COM shim 解决方案简洁.

I would however like to keep all the new development that we undertake using C# and wondered if there are any frameworks that minimise the overhead of doing this. I have looked at IPCChannel but I feel that this approach is not as neat as the COM shim solution.

谢谢,埃德

推荐答案

我遇到了同样的问题,我的解决方案是使用 远程处理.该项目基本上包括:

I had the same problem and my solution was to use remoting. Basically the project consisted of:

  • 独立于平台的 CalculatorRemote.dll 库,带有
    • CalculatorNative 带有 x32 P/Invoke 方法的内部静态类
    • RemoteCalculator 类派生自 MarshalByRefObject 使用了来自 CalculatorNative 的本地方法;
    • Platform-independent CalculatorRemote.dll library with
      • CalculatorNative internal static class with x32 P/Invoke methods
      • RemoteCalculator class derived from MarshalByRefObject which used native methods from CalculatorNative;

      因此,如果主应用程序以 x64 模式启动,它会生成一个 RemoteCalculator 主机应用程序并使用远程 RemoteCalculator 实例.(在 x32 中,它只使用 RemoteCalculator 的本地实例.)棘手的部分是告诉计算器主机应用程序关闭.

      So if the main application started in x64 mode it was spawning a RemoteCalculator host application and used remoted RemoteCalculator instance. (When in x32 it just used a local instance of RemoteCalculator.) The tricky part was telling calculator-host application to shut down.

      我认为这比使用 COM 更好,因为:

      I think this it better than using COM because:

      • 您不必在任何地方注册 COM 类;
      • 与 COM 的互操作应该比 .NET 远程处理慢;
      • 有时,如果 COM 端出现问题,您需要重新启动应用程序以从中恢复;(可能我只是对 COM 不太熟悉)
      • 在 x32 模式下运行时,远程处理不会有任何性能损失——所有方法都将在同一个 AppDomain 中调用.

      这篇关于使用托管代码包装器从 64 位托管代码调用 32 位非托管代码的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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