title: Calling C++ function with pointer to function in C# as parameter
body: <p>I have the following code in Native C dll.</p>
  
  <pre><code>typedef void CallbackType( INT32 param1, INT32 param2 );
  
  NATIVE_API void RegisterEventCallBack(CallbackType *callBackFunction);
  
  
  //INT32 is defined as below:
  
  typedef signed int          INT32, *PINT32;
  </code></pre>
  
  <p>I have to call this method from my C# code. After following some solutions available at stackflow, I tried this:</p>
  
  <p><strong>Declaration of delegate:</strong></p>
  
  <pre><code>[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
  public delegate void CallbackType(Int32 param1, Int32 param2); 
  </code></pre>
  
  <p><strong>Method import declaration:</strong></p>
  
  <pre><code>[DllImport("EtIPAdapter.dll")]
  public static extern void RegisterEventCallBack([MarshalAs(UnmanagedType.FunctionPtr)]CallbackType callbackFunc);
  </code></pre>
  
  <p><strong>Calling:</strong></p>
  
  <pre><code>RegisterEventCallBack(ReceivedData);
  
  private static void ReceivedData(Int32 param1, Int32 param2)
  {
      //Do something
  }
  </code></pre>
  
  <p>But this doesn't work and I get the following error:</p>
  
  <blockquote>
    <p>A call to PInvoke function 'RegisterEventCallBack' has unbalanced the stack. This is likely because the managed PInvoke signature does not match the unmanaged target signature. Check that the calling convention and parameters of the PInvoke signature match the target unmanaged signature.</p>
  </blockquote>
  
  <p>I also tried by passing the function pointer which I got using <code>GetFunctionPointerFromDelegate(ReceivedDataDelegate)</code>. But that also result in the same error. </p>
  
  <p>Error point out to signature mismatch, but I don't see any obvious signature mismatch. Please help.</p>