C# – Possible to call C++ code from C#


Is it possible to call C++ code, possibly compiled as a code library file (.dll), from within a .NET language such as C#?

Specifically, C++ code such as the RakNet networking library.

Best Solution

One easy way to call into C++ is to create a wrapper assembly in C++/CLI. In C++/CLI you can call into unmanaged code as if you were writing native code, but you can call into C++/CLI code from C# as if it were written in C#. The language was basically designed with interop into existing libraries as its "killer app".

For example - compile this with the /clr switch

#include "NativeType.h"

public ref class ManagedType
     NativeType*   NativePtr; 

     ManagedType() : NativePtr(new NativeType()) {}
     ~ManagedType() { delete NativePtr; }

     void ManagedMethod()
      { NativePtr->NativeMethod(); } 

Then in C#, add a reference to your ManagedType assembly, and use it like so:

ManagedType mt = new ManagedType();

Check out this blog post for a more explained example.