我试图在两种语言之间进行非常基本的互操作。我基本上有一些性能密集的代码,我想用C++来处理,然后将结果返回给我的应用程序。如何在C#和C++之间进行互操作
所有将在Visual Studio中编译。
我选择了int作为输入和输出类型,因为编组可能有点不可靠,而不是我真正处理的。
C++我有:
#include "stdafx.h" // default from vs2013, no idea what it is
_declspec(dllexport) int Diu(int p) {
return p * 2;
}
C#我有:
using System;
namespace Interop {
public class Program{
[System.Runtime.InteropServices.DllImport("Hardworker.dll")]
public static extern int Diu(int p);
private static void Main(string[] args) {
Console.WriteLine(Diu(2));
}
}
}
所以这是一个非常简单的例子。但我得到的例外:
An unhandled exception of type 'System.BadImageFormatException' occurred in Interop.exe
Additional information: An attempt was made to load a program with an incorrect format. (Exception from HRESULT: 0x8007000B)
C++项目创建为创建对话框中的控制台应用程序> Dll。 我在反汇编器中检查了C++ dll,我可以看到一个Diu作为导出的符号。
呃。我错过了关于设置互操作的问题?
不错。我的电脑是x64。我将编译设置为x86。并且该错误更改为EntryPointNotFoundException:无法在DLL'Hardwork.dll'中找到名为'Diu'的入口点。 – CyberFox
@CyberFox C++根据参数类型和函数的其他限定符来调整函数名称。您需要声明函数'extern“C”',以便使用名称导出而不会发生混乱。 –
@YngveHammesrland实际上工作。 2个答案在1。 – CyberFox