C#C
C#11mo ago
10 replies
nathanAjacobs

Managed callback to native code (reverse p/invoke)

If I pass a managed callback to native code, do I need to pin the stored delegate so it does not get moved to a new memory address or is this handled by the runtime?

public class MyTestClass
{
    private delegate void NativeTestCallback(int num);

    [DllImport("TestNative")]
    private static extern void NativeFunc(NativeTestCallback callback);

    private NativeTestCallback _callback;
    public MyTestClass()
    {
        // do I need to pin this?
        _callback = TestCallback;
        NativeFunc(_callback);
    }

    private void TestCallback(int num)
    {

    }
}
Was this page helpful?