Define an interface in C++ that needs to be implemented in C# and C++-Collection of common programming errors
You don’t mention which version of .NET you’re using, but something that’s worked for me in using Visual Studio .NET 2003 is to provide a thin C# wrapper around the pimpled implementation of the real C++ class:
public __gc class MyClass_Net {
public:
MyClass_Net()
:native_ptr_(new MyClass())
{
}
~MyClass_Net()
{
delete native_ptr_;
}
private:
MyClass __nogc *native_ptr_;
};
Obviously, one would prefer to use a Boost shared_ptr there, but I could never get them to play nicely with V.NET 2003…
Methods simply forward to the underlying C++ methods through the pointer. Method arguments may have to be converted. For example, to call a C++ method which takes a string, the C# method should probably take a System.String (System::String in Managed C++). You’d have to use System::Runtime::InteropServices::Marshal::StringToHGlobalAnsi() to do that.
One nice thing about this approach is because Managed C++ is a .NET language, you get to expose accessors as properties (__property). You can even expose attributes, very much like in C#.