public class SendImage
{
public delegate int DWatch(int bytesLeftToSend, IntPtr Response);
ret=0xffff;
public void ReadImageFile()
{
int len = 1495;
DWatch pfWatch = DResponse;
IntPtr pfMethod = Marshal.GetFunctionPointerForDelegate(pfWatch);
ret=Send(len, pfMethod);
}
public int DResponse(int bytesLeftToSend, IntPtr Response)
{
//something;
return 0;
}
}
The above code shows the marshalling of delegate to into function pointer how I did. From this I was able to callback. But later I am getting memory corrupt error. Please help. Thanks
//unmanaged call in code
int Send(int length, int(*pfMethod)(int bytesLeftToSend, void * Response))
{
int Remaining = 50;
pfMethod(50);
}
Your program will fall over when the garbage collector runs and deletes the delegate instance. The one that was once referenced by your pfWatch local variable. But no more, that variable is long gone, zapped when ReadImageFile() returned. The collector cannot see references being held by unmanaged code.
You have to keep a reference yourself and store it in a place that the collector can see. pfWatch must at least be a field in your class instead of a local variable. Possibly static so it never gets garbage collected. It isn’t otherwise clear from your snippet when the native code stops making callbacks.