C# – Writing a C++ DLL, then wrapping it in C#

bindingc++dllwrapper

I am a bit confused about wrapping a c++ dll in c#.
What kind of dll should i create? A normal dll or an mfc dll? Should i prefix every proto with "extern…" ? Should i write the functions in a def file?

My last effort was in vain, c# would crash with an error like "bad image format", which means that the dll format is not correct?

Any help would be much appreciated.

Thanks in advance 🙂

Best Solution

Are you using a 64-bit PC?

"Bad image format" will occur on an x64 system if you try to mix x64 code and x86 code. This will happen if you write C# code (targeted to "Any CPU", so it'll jit-compile to x64 code) that calls an unmanaged DLL (that will probably be x86 by default).

Two solutions to this are:

  • (Proper solution) Make sure the dll is compiled to target x64 so the whole program can run as a native 64-bit app, or
  • (Backwards compatibility solution) Force your whole application to run as an x86 app. In the C# project properties, change the Build "Any CPU" setting to "x86".

Otherwise, you should be able to create a normal COM dll (with or without MFC shouldn't matter) and then just wrap it in an RCW (Runtime callable wrapper).

Related Question