2010-09-29 69 views
0

如何從C++ DLL調用函數?C#接口C++ DLL?

的C++ DLL包含功能是這樣的:

__declspec(dllexport) bool Setup() { return simulation.Setup(); } 

的C#程序執行此:

[DllImport("mydll.dll")] 
[return: MarshalAs(UnmanagedType.Bool)] 
public static extern bool Setup(); 

的C#程序崩潰並顯示以下消息,當它試圖加載DLL(?) :

An unhandled exception of type 'System.BadImageFormatException' occurred in TestFrame.exe 

Additional information: There was an attempt to load a file with a wrong format (exception from HRESULT: 0x8007000B) 

The C++ DLL is a standard DLL (no MFC, no ATL). 
+1

64位.NET程序集嘗試加載32位本機.dll?反之亦然? – 2010-09-29 20:40:29

+0

谷歌翻譯爲'嘗試加載格式不正確的程序。 (來自HRESULT的異常:0x8007000B)' – SLaks 2010-09-29 20:40:40

+0

這是在64位操作系統上嗎?如果.NET應用程序編譯爲AnyCPU並且C++ dll爲32位,則dll將不會加載。 – 2010-09-29 20:41:19

回答

2

當您嘗試將32位DLL加載到64位進程中時,會發生此錯誤。 (反之亦然)
在VS2010之前,C#項目默認爲任何CPU,並且將在64位操作系統上以64位運行。

您需要轉到「項目屬性」中的「生成」選項卡,並將C#項目設置爲x86。

1

是否有可能您的exe和dll有不同的位數(即一個是64和th e其他32)?

0

您是否試過編譯x86平臺的代碼? 有關說明,請參閱this博客文章。