Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing Data From C++ to C#

Tags:

c++

c#

.net

sockets

I am looking into developing a C# app which needs to be called from a legacy unmanaged C++ app. The C# app will create a Winforms or WPF window (still researching which to go with) which has a third party control in it. First of all, I looked into using a C++/CLR wrapper class to call it and then COM Interop. Both of these methods were fine until the third party control was added to the form. The company who produce this control stated that they would not support their product when called from unmanaged C++.

I am now considering alternatives where the C# app is a standalone app which I can then pass data from the C++ app possibly through Sockets or similar.

I was wondering if anyone could recommend the best way to do this. I have considered sockets or memory mapped files. I am not sure what is the best method or if there is a better one.

like image 372
TimR75 Avatar asked Mar 15 '23 12:03

TimR75


2 Answers

From my experience is far more easy to call c++ code from c# through c++/CLI wrappers than the other way around. I would try to write an active requester from the C# app that would ask for the information to the c++ code through a c++/CLI wrapper.

It doesn't matter who consumes the data or who is responsible for producing the data. It's just a matter of structuring the calls

c++ code

bool do_you_have_something_for_me();
void get_data_from_cpp_code(HugeStructure &response);

c++/CLI code

ref class Wrapper
{

   public bool waitForRequestCppCode()
   {
       if(do_you_have_something_for_me())
       {
          //call get_data_from_cpp_code and put the result in a nice .NET class
          return true;
       }
       else return false;
   }
}

c# code

while(!waitForRequestCppCode())
{
   //Do C# app stuff
}
//access the info from the wrapper and act, rinse and repeat

This is just a very rough code, probably with a lot of mistakes, just to prove a point.

like image 168
Diego O.d.L Avatar answered Mar 24 '23 06:03

Diego O.d.L


In C#, you can create a subclass of System.EnterpriseServices.ServicedComponent to create a COM+ service which can be called from unmanaged code (with CoCreateInstance).

Look at this article for more informations: https://msdn.microsoft.com/en-us/library/ms973847.aspx

like image 33
Maxence Avatar answered Mar 24 '23 04:03

Maxence