Daniel Baulig
Daniel Baulig

Reputation: 10989

Receiving an object in a unmanaged callback function

Eg. I have following delegate method I want to use as a callback function with unmanaged code:

public delegate void Callback(IntPtr myObject);

Callback callback;

I register it in the following way:

[DllImport("a.dll")]
public static void registerCallback(IntPtr callbackFunction, IntPtr anObject); 

// ...

this.myObject = new MyClass();
this.objectPin = GCHandle.Alloc(this.myObject, GCHandleType.Pinned);
registerCallback(Marshal.GetFunctionPointerForDelegate(callback), objectPin.AddrOfPinnedObject());

Now whenever the callback function is called it will have a Pointer/Handle of an object of the MyClass class. I could use Marshal.PtrToStructure to convert this to an object of MyClass. However, what I would like to have is that the delegate definition already contains the class MyClass. eg.:

public delegate void Callback(MyClass myObject);

I tried this, but it will not work. I also tried the following, which did not work:

public delegate void Callback([MarshalAs(UnmanagedType.IUnknown)]MyClass myObject);

I suppose I would need something like "UnmarshalAs" at this point, but sadly this is not available. Any suggestions how I could get lost of that IntPtr in my callback function and get a it packed up as a regular, managed MyClass object?

Upvotes: 0

Views: 758

Answers (1)

dtb
dtb

Reputation: 217313

GCHandle.FromIntPtr Method:

void MyCallback(IntPtr anObject)
{
    GCHandle gch = GCHandle.FromIntPtr(anObject);
    MyClass myObject = (MyClass)gch.Target;
}

Upvotes: 2

Related Questions