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)
{

}
}
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)
{

}
}
4 Replies
Mąż Zuzanny Harmider Szczęście
all you need to do is make it static i think
nathanAjacobs
nathanAjacobsOP8h ago
Yeah I could, but I'm curious specifically about the semantics of an instanced callback. For example, I could have an unmanaged and managed representation of a class and have an instance id to track it between creation and disposal on the native side
Mąż Zuzanny Harmider Szczęście
then ig u have to pin it, not really sure tho
nathanAjacobs
nathanAjacobsOP6h ago
Yeah that's what I'm thinking too, but wanted to get confirmation

Did you find this page helpful?