title: How to handle C++ Native Callback Class in managed wrapper
body: <p>I've seen the possible duplicate but the semantics are slightly different so I havent' been able to get it working until now. I'm not even sure it is really comparable to the pure c-function pointer style, which I've already used in different projects.</p>
  
  <p>I have a DLL which defines a native C++ callback like this:</p>
  
  <pre class="lang-or-tag-here prettyprint-override"><code>class NativeClass
  {
  
  // Native Callback Handler class, internal definition
  class Callback
  {
  public:
    // Constructor
    Callback() {}
    // Destructor
    virtual ~Callback() {}
  
    // Callback functions
    virtual void Handler() {}
  };
  
  SetCallback(Callback* p)
  {
     ...
  }
  ...
  </code></pre>
  
  <p>The DLL then consumes and fires the Callback by this function:</p>
  
  <pre><code>SetCallBack(NativeClass::Callback* p);
  </code></pre>
  
  <p>So when I'm writing my C++/CLI wrapper, how can I pass a reference to a managed object exposing such a callback handler.</p>
  
  <p>Is something like this generally not possible or how would I have to handle that
  correctly ? 
  I've tried the following now according to the MSDN documentation and other SO answers:</p>
  
  <pre><code>typedef (__stdcall *NATIVE_CALLBACK)(void);
  
  public delegate void ManagedCallback();
  
  ...
  
  public ref class Wrapper
  {
  public:
  
  Callback*    _CBHandlerNative;
  NativeClass* nc; 
  
  Wrapper()
  {
      _CBHandlerNative = new NativeClass::Callback();
      _nc              = new NativeClass();
  
  
      // try assigning function pointer, but fails 
  
     IntPtr ip = Marshal::GetFunctionPointerForDelegate(gcnew ManagedCallback(this, &amp;Wrapper::ToBeCalled));
     _CBHandlerNative-&gt;Handler = static_cast&lt;NATIVE_CALLBACK&gt;(ip.ToPointer());
  
       _nc-&gt;SetCallback(_CBHandlerNative);
  
  }
  
  // managed handler
  void ToBeCalled()
  {
    ...
  }
  </code></pre>