如何从C#调用混合模式的C++/CLI程序集?

4
我已经编写了一个混合模式的C++/CLI程序集,它包装了一个本地的C++库。它成功地编译了。我可以编写一个使用该程序集的C++/CLI应用程序,所以我知道它能工作。
因此,我编写了一个使用相同C++/CLI程序集的C#应用程序。这也编译通过。但是当我尝试运行它时,我会收到"BadImageFormatException"的错误,下面是详细的异常信息。
我认为这个异常是因为我的程序集是混合模式的,因此是"不安全的"。但是从我读过的资料来看,即使是不安全的程序集在本地硬盘上运行时也应该被信任,而我正在这样做。
有人能帮助我理解这里发生了什么吗?我正在尝试做的事情可能吗?
详细的异常信息:
System.BadImageFormatException was unhandled Message="Could not load file or assembly 'asillyclass, Version=1.0.3988.20325, Culture=neutral, PublicKeyToken=null' or one of its dependencies. An attempt was made to load a program with an incorrect format." Source="ConsoleApplication1" FileName="asillyclass, Version=1.0.3988.20325, Culture=neutral, PublicKeyToken=null" FusionLog="=== Pre-bind state information === : User = SIG\\user : DisplayName = asillyclass, Version=1.0.3988.20325, Culture=neutral, PublicKeyToken=null\n (Fully-specified) : Appbase = file:///C:/projects/API/TestApp-C#/ConsoleApplication1/bin/Debug/ : Initial PrivatePath = NULL assembly : ConsoleApplication1, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null. === : This bind starts in default load context. : Using application configuration file: C:\\projects\\API\\TestApp-C#\\ConsoleApplication1\\bin\\Debug\\ConsoleApplication1.vshost.exe.config : Using machine configuration file from C:\\Windows\\Microsoft.NET\\Framework64\\v2.0.50727\\config\\machine.config. : Policy not being applied to reference at this time (private, custom, partial, or location-based assembly bind). : Attempting download of new URL file:///C:/projects/API/TestApp-C#/ConsoleApplication1/bin/Debug/asillyclass.DLL. : Failed to complete setup of assembly (hr = 0x8007000b). Probing terminated. " StackTrace: at ConsoleApplication1.Program.Main(String[] args) at System.AppDomain._nExecuteAssembly(Assembly assembly, String[] args) at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly() at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state) at System.Threading.ThreadHelper.ThreadStart() InnerException:
1个回答

9

最有可能的原因是您正在运行64位操作系统,并且存在32/64位不匹配(例如,DLL为32位,而应用程序为64位/AnyCPU)。

要解决此问题,请转到您应用程序的属性并选择x86,而不是AnyCPU。


1
微软真的需要修复这个错误信息,因为几乎每个C++/CLI程序员都会遇到它至少一次。应该不难包含“当前进程是x86_64,但库只能在x86(32位)环境中加载”的信息。(如果您尝试加载为WinCE设计的DLL,则为Itanium、ARM或MIPS) - Ben Voigt
1
这个问题已经得到了一定的缓解,因为很多人都遇到过。通过谷歌搜索很快就能找到答案。VS2010默认将应用程序设置为x86而不是AnyCPU。话虽如此,如果你打开一个Connect问题,我会点赞的。 :) - Stephen Cleary
谢谢!这很有帮助,尽管我实际上重新编译了DLL以针对x64。我找不到应用程序属性中的“平台目标”设置,有什么原因吗?Visual C# Express版本可能没有公开此设置,还是我只是错过了它? - Alton Patrick
好的,我回答了自己的问题:Express版本在GUI中没有公开此设置,但是您可以手动编辑csproj文件来更改它。现在它正在工作;感谢您的答案! - Alton Patrick

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接