I'm trying to pass a C# callback function to a native dll. It works fine, but I couldn't find a way to access the parent object of the callback method. Here's a code which demonstrates what I want to do:
class MyForm: Form {
public delegate void CallbackDelegate(IntPtr thisPtr);
[DllImport("mylib.dll", CallingConvention = CallingConvention.StdCall)]
public static extern void Test(CallbackDelegate callback);
int Field;
static void Callback(IntPtr thisPtr)
{
// I need to reference class field Field here.
MyForm thisObject = ?MagicMethod?(thisPtr);
thisObject.Field = 10;
}
void CallExternalMethod()
{
Test(Callback);
}
}
I tried getting the pointer of this
but I got the following exception: "Object contains non-primitive or non-blittable data.". I should probably mention that the parent object is a WindowsForms form.
UPDATE
The dll is written in Delphi and the signature of the Test function is the following:
type
TCallback = procedure of object; stdcall;
procedure Test(Callback: TCallback); stdcall;
I received the above error message when I tried to get the pointer to the class with the following code:
var ptr = GCHandle.Alloc(this, GCHandleType.Pinned).AddrOfPinnedObject();