views:

233

answers:

1

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 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!

+1  A: 

This errors 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.

Chris Schmich
I m using a 64 bit machine. But all the projects are in 32 bit platform and I can't even change the platform target in C++ dll project other than "Win 32". In C# project properties also the build target can only be set as "any CPU". However I managed to access the dll methods from a C# web service. I having this issue when using a C# windows application.
chathuradd
Why can't you change the C# project from AnyCPU? What kind of project is it? An AnyCPU project on a 64-bit machine will run as 64-bit. When it tries to load your Win32 (32-bit) C++ DLL, it will fail with the exception your seeing. You should either change the C# project to be x86 or change the C++ DLL project to be x64.
Chris Schmich
Sorry. I have looked in the wrong place it seems. yes I could change the platform to x86 in C#, so now the exception is not being thrown.Thanks a lot :)
chathuradd