SWIG

SWIG (Simplified Wrapper and Interface Generator) can generate wrappers for C or C++ libraries.

C++ to C# Example
This example is done using the Microsoft C++ compiler (cl), but it should be the same on other platforms, except for the C++ compilation.

Code to Wrap
thing.h:
 * 1) include

// Nested classes currently not supported by SWIG, so it is here instead // of in Thing struct Some_problem_exception { };

class Thing { public: Thing(int x) : x(x) {}

void do_stuff; std::string get_some_string; void throw_exception throw(Some_problem_exception);

// public member variable results in C# property int x; };

thing.cpp:
 * 1) include "thing.h"

void Thing::do_stuff { x = x * x; }

std::string Thing::get_some_string { return std::string("this is some string"); }

void Thing::throw_exception { throw new Some_problem_exception; }

Running SWIG
Define interface in thing.i: %module ThingTest

%{ %}
 * 1) include "thing.h"

// we use strings and exceptions, so we have to specify that here: %include std_string.i %include exception.i

%include "thing.h" And then run SWIG: swig -Wall -csharp -c++ thing.i

Compile DLL
SWIG generates wrapper code in thing_wrap.cxx, which must be compiled with the rest of the thing: cl /EHsc /LD thing.cpp thing_wrap.cxx /o thingtest.dll /EHsc : enable exception handling /LD  : create dll /o   : specify output file

C# Test
Here, we change ThingTest.cs: using System; using System.Runtime.InteropServices;

public class ThingTest { public static void Main { Thing thing = new Thing(4); Console.WriteLine("thing.x: {0}", thing.x); Console.WriteLine("thing.get_some_string: {0}", thing.get_some_string); thing.throw_exception; } } And compile (using Mono in this case): gmcs -main:ThingTest -out:thing.exe *.cs

MinGW
Using MinGW, you can get problems with name mangling. Adding %include "windows.i" to the start of your swig interface file should resolve the problems.

Possible Problems
The following error: $ mono TestSomeLibrary.exe Unhandled Exception: System.TypeInitializationException: An exception was thrown by the type initializer for SomeLibraryPINVOKE ---> System.TypeInitializationException: An exception was thrown by the type initializer for SWIGExceptionHelper ---> System.DllNotFoundException: SomeLibrary does not necessarily mean that mono cannot load the 'SomeLibrary' library, but if 'SomeLibrary' requires other libraries, they may be the problem. On Mac OS X, the problem can be resolved like this: DYLD_LIBRARY_PATH=/path/to/library/:/other/path/ mono TestSomeLibrary.exe