I have a native function which accepts a pointer to function which should be called periodically throughout the lifetime of the process. This function is exported from the dll where it is defined.
Now, from managed code I want to call this function with my delegate as an argument. Also my delegate is a non-static one (it references this).
So:
[UnmanagedFunctionPointer(CallingConvention.Winapi)]
public delegate void MyDelegate([MarshalAs(UnmanagedType.LPWStr)] string myString);
[DllImport("mydll")]
public static extern int DelegateSet(MyDelegate);
public void MyFunc(string myString)
{
// Do something here.
}
// Somewhere in managed code:
DelegateSet(MyFunc);
And this works but only for the short time. Native code calls this callback a couple of times and then I hit an AV. My guess is that garbage collector moves the object which contains the delegate and native code has a loose reference.
I would appreciate any pointers on how to proceed.