开发者

how to call a C++ dll from C# windows application project

I have created a dll in C++ using a Class Library project in Visual Studio. I need to call a method in the dll from a C# application.

I got to know there are 2 approches. One is to add the dll project reference to C# project or use DllExport to export method. However when I tried in both开发者_JAVA百科 ways it always gives the following error when the dll method is called in runtime.

An unhandled exception of type 'System.BadImageFormatException' occurred in TestClient.exe Additional information: An attempt was made to load a program with an incorrect format. (Exception from HRESULT: 0x8007000B)

Can i know how to avoid this problem ?

Thanks in advance!


This error means that you're trying to load a 32-bit DLL into a 64-bit process or a 64-bit DLL into a 32-bit process. On Windows, the bitness of the DLL must match the bitness of the process in order for it to load correctly.

Is your native DLL 32- or 64-bit? In your C# project build settings, what platform are you targeting? If you go into the C# project properties, you can go to the Build tab and change the "Platform target" to something specific like x86 or x64 to match the platform that your native DLL was built for.

The other alternative would be to build the native DLL to match the platform of your C# application. If the C# application's platform is AnyCPU, though, it will run as 32-bit on 32-bit Windows and 64-bit on 64-bit Windows. Because of this, you would need both a 32- and 64-bit version of your native DLL.

I would recommend setting your C# application's platform to something specific (x86, x64) and then change your native DLL's platform to match.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜