Possible to call C++ code from C#?

yiingchau picture yiingchau · Jun 1, 2009 · Viewed 98.4k times · Source

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.

Answer

Eclipse picture Eclipse · Jun 1, 2009

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; 

public:
     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();
mt.ManagedMethod();

Check out this blog post for a more explained example.