2016-11-09 45 views
5

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

呃。我錯過了關於設置互操作的問題?

回答

4

當您收到此錯誤:HRESULT: 0x8007000B是由於平臺不兼容導致的。
檢查您的編譯器配置文件是否設置爲相同平臺(x86x64AnyCPU)。

+0

不錯。我的電腦是x64。我將編譯設置爲x86。並且該錯誤更改爲EntryPointNotFoundException:無法在DLL'Hardwork.dll'中找到名爲'Diu'的入口點。 – CyberFox

+1

@Cyber​​Fox C++根據參數類型和函數的其他限定符來調整函數名稱。您需要聲明函數'extern「C」',以便使用名稱導出而不會發生混亂。 –

+0

@YngveHammesrland實際上工作。 2個答案在1。 – CyberFox

相關問題