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

标签 c# c++-cli

我编写了一个混合模式的 C++/CLI 程序集,它包装了一个 native 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: 

最佳答案

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

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

关于c# - 如何从 C# 调用混合模式 C++/CLI 程序集?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4338879/

相关文章:

c# - SQL Server 在哪里存储已部署的 CLR 程序集?

c# - 从 .aspx 中永远不会在 aspx.cs 中调用 delete 函数

algorithm - 向树中添加节点的函数

documentation - 记录 C++/CLI 库代码以供 C# 使用 - 最佳工具和实践?

vector - 是否可以从函数返回两个向量?

c# - 从数据库生成一个连续的数字

c# - 如何在 ASP.NET MVC 4 Razor 项目的 View 中显示集合?

c# - LINQ 获取类的属性

c++-cli - 如何在 headers/body 中正确定义 c++/cli 中的属性

c++ - 将 C++/CLI 转换为 C++ 时的陷阱