如何在 C# 和 C++ 之间进行互操作
How to Interop between C# and 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 作为导出符号。
呃。关于设置互操作,我错过了什么?
出现此错误时:HRESULT: 0x8007000B
是由于平台不兼容造成的。
检查您的编译器配置文件是否设置为相同的平台(x86
、x64
或 AnyCPU
)。
我正在尝试两种语言之间的非常基本的互操作。我基本上有一些我想用 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 作为导出符号。
呃。关于设置互操作,我错过了什么?
出现此错误时:HRESULT: 0x8007000B
是由于平台不兼容造成的。
检查您的编译器配置文件是否设置为相同的平台(x86
、x64
或 AnyCPU
)。