Receiving an object in a unmanaged callback function

Posted by Daniel Baulig on Stack Overflow See other posts from Stack Overflow or by Daniel Baulig
Published on 2010-04-17T19:31:37Z Indexed on 2010/04/17 19:33 UTC
Read the original article Hit count: 360

Filed under:
|
|
|

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?

© Stack Overflow or respective owner

Related posts about c#

Related posts about unmanaged