0

In C++ it's common to pass the 'this' pointer to a callback registration method so that the callback will receive this pointer back. I have a 3rd party library that i am trying to interop with from C# that uses this pattern.

Ex.

typedef HRESULT (WINAPI PFNCALLBACK*)(CALLBACKDATA *data, void *context);

HRESULT SetCallback (PFNCALLBACK *callback, void *context);

I've defined a delegate for the callback function:

public delegate int Callback(IntPtr context, CallbackData sample);

and call the SetCallback function

void SetupCallback()
{
  // My stab at passing the this pointer as context for the callback
  IntPtr pThis = GCHandle.ToIntPtr(GCHandle.Alloc(this));
  hr = obj.SetCallback(OnCallback, pThis);
}

public static int OnCallback(CallbackData data, IntPtr context)
{
   // HOW do I reconstitute the This pointer from the context parameter
}

My question is how do I pass a C# 'this' pointer to the SetCallback method and reconstitute it in the callback function?

wta
  • 78
  • 7

1 Answers1

1

Ugh, you are asking for an interop nightmare, especially since you are dealing with a "black box" third party DLL.

Having said that, theoretically this should be possible by utilizing the UnmanagedFunctionPointer attribute.

[UnmanagedFunctionPointer(CallingConvention.StdCall)]
public delegate int Callback(IntPtr context, CallbackData sample);

Then store off your delegate

static Callback _someCallBack = null;
_someCallBack += new Callback(OnCallback);

Finally pass in the delegate when calling the C code

IntPtr pThis = GCHandle.ToIntPtr(GCHandle.Alloc(this));
hr = obj.SetCallback(_someCallBack, pThis);

I also don't think you even really need to mess with the this pointer, unless you really need it in the callback honestly I would try passing in null. It's not safe in .Net land to marshall and marshall references back and re-use it.

Tim
  • 2,878
  • 1
  • 14
  • 19
  • Actually, I am dealing with a black box .lib file for which I created a dll that wraps it. The .lib has a function that creates an unregistered COM object. The COM object has an interface with the callback registraton method. – wta Aug 26 '16 at 02:10