2010-09-29 79 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博客文章。