title: C++/CLI callback to C#
body: <p>I have a C library (DLL) where I have callback functions with defined datatypes.</p>
  <p>Now I am writing Wrapper(DLL) for this in C++/CLI. This Wrapper Dll will be used in my C# application.</p>
  <p>How to Implement the callback in C++/CLI so that i can write the call back function in C# an passt it through the wrapper to the C librarby.</p>
  <p>Dll Libray ...</p>
  <pre><code>
  # C libary (DLL) *.h file
  ...
  typedef void (*TOnMonitoringStateCB)(const ROBOT_STATE);
  typedef void (*TOnMonitoringDataCB)(const LPMONITORING_DATA);
  ...
  DRFL_API void _SetOnMonitoringState(LPROBOTCONTROL pCtrl, TOnMonitoringStateCB pCallbackFunc);
  DRFL_API void _SetOnMonitoringData(LPROBOTCONTROL pCtrl, TOnMonitoringDataCB pCallbackFunc); 
  ...
  class CDRFL
  {
  public:
      // robot status data
      void SetOnMonitoringState(TOnMonitoringStateCB pCallbackFunc) { _SetOnMonitoringState(_rbtCtrl, pCallbackFunc); };
      // robot operating data
      void SetOnMonitoringData(TOnMonitoringDataCB pCallbackFunc) { _SetOnMonitoringData(_rbtCtrl, pCallbackFunc); };
  ...
  
  </code></pre>
  <p>Wrapper (DLL) C++/CLI ...</p>
  <pre><code>
  # C++/CLI *.h (my try)
  ...
  public delegate void ManagedTOnMonitoringStateCB(const RobotState);
  public delegate void ManagedTOnMonitoringDataCB(const LpMonitoringDate);
  ...
  public ref class WrapperClass
  {
     ...
     void SetOnMonitoringState(ManagedTOnMonitoringStateCB^ callbackFunc);
     void SetOnMonitoringData(ManagedTOnMonitoringDataCB^ callbackFunc);
     ...
  }
  # *.cpp (my try)
  ...
  void WrapperClass::SetOnMonitoringState(ManagedTOnMonitoringStateCB^ callbackFunc)
  {
      IntPtr cbPtr = System::Runtime::InteropServices::Marshal::GetFunctionPointerForDelegate(callbackFunc);
      _rbtCtrl-&gt;SetOnMonitoringState(static_cast&lt;CLibrarbyc::TOnMonitoringStateCB&gt;(cbPtr.ToPointer()));
  };
  void WrapperClass::SetOnMonitoringData(ManagedTOnMonitoringDataCB^ callbackFunc)
  {
      IntPtr cbPtr = System::Runtime::InteropServices::Marshal::GetFunctionPointerForDelegate(callbackFunc);
      _rbtCtrl-&gt;SetOnMonitoringData(static_cast&lt;CLibrarbyc::TOnMonitoringDataCB&gt;(cbPtr.ToPointer()));
  };
  ...
  
  </code></pre>
  <p>C# ...</p>
  <pre><code>
  ...
  _rbtCtrl.SetOnMonitoringState(OnMonitoringState());
  
   void OnMonitoringState()
   {
       textBox1.AppendText(&quot;...&quot;);
   }
  
  _rbtCtrl.SetOnMonitoringData(OnMonitoringData());
  
   void OnMonitoringData()
   {
       textBox1.AppendText(&quot;...&quot;);
   }
  ...
  
  </code></pre>
  <p>The C++/CLI seems to be OK, but in the C# part I always have problems with the Converting the types.
  It also can be a problem of the initialisaten of the callbackfunction and the handling of the function in C#.
  But maybe there is also and erro in the C++/CLI Wrapper or it can be done easier, but it compiles.</p>