Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call (C#) .NET Core method from C++

I have 2 components:
- .Net Core Application running on Ubuntu OS.
- C++ shared library (.so)

Now I want C++ component to be able to call .Net Core method, either passing interface to C++ component which will use this interface to callback method implementation or passing method as a parameter to C++ component.

High-level example what I am trying to achieve:
C# component :

public interface IDevice
{
   void OnDataAvailable(string data);
}

public class Device: IDevice
{
   [DllImport("sampleCPPLibrary.so")]
   private static extern int SetReceiver(IDevice receiver);  
   public void OnDataAvailable(string data)
   {
      Console.WriteLine(data);
   }
   public void Initialize()
   {
      SetReceiver(IDevice(this))
   }
}

C++ component:

extern "C" {
void SetReceiver(IReceiver * receiver)
{
    receiver->OnDataAvailable(10);
}
}

Basically, what I am trying to do is just to pass some kind of "callback" to C++ component and call this "callback" when some event occurs in C++ component.

like image 604
Andrew K Avatar asked Oct 18 '17 14:10

Andrew K


Video Answer


1 Answers

See See this issue from comments I constructed code where C# calls C and gives it callback delegate. Thus from C then it calls C#, and passes additional int type argument. See comments here from endurox project, and attached c-callback.tar.gz for working example.

like image 186
Madars Vi Avatar answered Oct 16 '22 14:10

Madars Vi