Calling C# method from C++

In a way, Interfaces is very similar to virtual class. The difference is that the interface is only defining the signatures of the methods, while the virtual class can optionally provide a method implementation.

One use of interface is to write call back methods from C++ to C#.

You need to first define the interface:

public interface class ICallback
{
public:
virtual void func(Platform::String ^message);
};

And then add an implementation in C#

public class CallbackImpl : ICallback
{
public virtual void sayMessage(Platform::String ^message);
{
System.Diagnostics.Debug.Write(message);
}
}

Finally use it as the following:

C++:

class A {
void DoSth(ICallback Callback)
{
Callback->sayMessage( Hello World );
}
}

C#:

class B {
void funcB(void) {
A a = new A();
a.DoSth( new CallbackImpl() );
}
}

Software Engineer in the day. At night and over the weekend, I play with various stuff and write about them, either related or not related to work.