.NET 应用程序加载混合 dll,使用任何 CPU

Bjo*_*ern 5 .net mixed-mode anycpu

我是创建 .NET 应用程序的新手,尤其是混合应用程序。

最近,我在(非托管)C++(在 MS Visual Studio 2010 下)中为客户端创建了一组(静态)库,支持 32 位和 64 位编译,由某些应用程序加载,通常很好. (在内部,此功能使用各种其他第三方库,如 OpenGL、boost、glm 等)

现在,他还希望能够在他的 C# 应用程序中使用我作为自定义控件提供的一些功能。

所以我创建了一个支持 CLR 的 dll,使用 C++/CLI 为我的功能创建包装类,然后创建一个自定义的 WPF 控件,它是公共的(因此可以从外部访问),再次在两者中构建都可以正常工作32 位和 64 位。

然后为了测试,我创建了一个简单的 C# 应用程序(它真的很简单,因为我是 C# 新手,我的背景是 C/C++),它可以内置 32 位或 64 位,并且可以成功地从我的 DLL 加载控件并做它应该做的事情。

我现在遇到的问题是,他说他只想将单个可执行文件作为“任何 CPU”分发,然后根据启动位置加载适当的代码(即 32 位或 64 位)。

所以我所做的是在 C# 测试项目中添加一个“Any CPU”配置,并将“build”选项卡下的“platform target”设置为“Any CPU”。但现在我不确定在配置管理器下为其他项目设置什么平台(即 C++ 静态库,由 C++/CLI 混合模式 dll 使用)。所以为了测试我把它留在 x64 上,但是当我构建它时,我收到警告:

Warning MSB3270: There was a mismatch between the processor architecture of the project being built "MSIL" and the processor architecture of the reference "(name of my 64 bit dll)", "AMD64".  <br /> 
This mismatch may cause runtime failures. Please consider changing the targeted processor architecture of your project through the Configuration Manager so as to align the processor architectures between your project and references, or take a dependency on references with a processor architecture that matches the targeted processor architecture of your project.
Run Code Online (Sandbox Code Playgroud)

然而,它运行良好,即使它给了我那个警告。当我将其他项目设置为“Win32”时,我收到相同的警告,只是提到“x86”,但在这种情况下,它在启动时抛出异常,说“PresentationCore.dll 中发生了类型为‘System.BadImageFormatException’的未处理异常”

那我需要把它改成什么?如何让它加载可执行文件,然后决定加载哪个 dll?我真的不知道如何继续并让它按照我要求的方式工作。

Bjo*_*ern 2

我在一篇有关使用 Perforce 库的文章中找到了该问题的解决方案:

http://scottbilas.com/blog/automatically-choose-32-or-64-bit-mixed-mode-dlls/

本质上,您必须创建一个代理 dll,它是您的输出目标,并用作托管 C#(在我的例子中为 WPF)应用程序的参考。

然后,您创建该 dll 的 x64 和 x86 版本,并将其与可执行文件一起提供。您必须确保代理 dll 不与可执行文件一起存在。

启动时,您为 AppDomain.CurrentDomain.AssemblyResolve 创建一个事件处理程序,当找不到代理 dll 时将触发该事件处理程序。

然后根据您是在 32 位还是 64 位环境中,它可以选择正确的 dll 并加载它。