views:

78

answers:

1

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?

+1  A: 

GCHandle.FromIntPtr Method:

void MyCallback(IntPtr anObject)
{
    GCHandle gch = GCHandle.FromIntPtr(anObject);
    MyClass myObject = (MyClass)gch.Target;
}
dtb
I was just about to get back to tell I found a way casting GCHandöe to an IntPtr and vice versa when I saw your updated answer. Thanks alot man :)
Daniel Baulig