我試圖在兩種語言之間進行非常基本的互操作。我基本上有一些性能密集的代碼,我想用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