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?