tags:

views:

74

answers:

4

How do I call functions from a C++ DLL?

The C++ DLL contains functions like this:

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

The C# program does this:

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

The C# program crashes with the following message when it tries to load (?) the 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  A: 

Is it possible that your exe and dll have different bitness (i.e. one is 64 and the other 32)?

On Freund
+1  A: 

This error occurs when you try to load a 32-bit DLL into a 64-bit process. (Or vice-versa)
Until VS2010, C# projects are target any CPU by default and will run as 64-bit on a 64-bit OS.

You need to go to the Build tab in Project Properties and set the C# project to x86 only.

SLaks
A: 

Have you tried compiling the code for x86 platform? See this blogpost for instructions.

gaearon
A: 

It may not be appropriate for you to set the CPU architecture (platform target) for the assembly, but instead you can specify an alternate path to find the correct DLL to load.

http://stackoverflow.com/questions/3638751/ho-to-use-the-correct-unmanaged-dll-according-cpu-architecure-32-64bits/3639402#3639402

Greg Domjan