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;
}
}
上面的代码显示了我是如何将委托(delegate)编码为函数指针的。由此我能够回调。但后来我收到内存损坏错误。请帮忙。谢谢
//unmanaged call in code
int Send(int length, int(*pfMethod)(int bytesLeftToSend, void * Response))
{
int Remaining = 50;
pfMethod(50);
}
最佳答案
当垃圾收集器运行并删除委托(delegate)实例时,您的程序将崩溃。曾经被您的 pfWatch 局部变量引用的那个。但仅此而已,该变量早已不复存在,在 ReadImageFile() 返回时消失。收集器看不到非托管代码持有的引用。
你必须自己保留一个引用并将其存储在收藏者可以看到的地方。 pfWatch 必须至少是您类中的一个字段而不是局部变量。可能是静态的,所以它永远不会被垃圾收集。当 native 代码停止进行回调时,从您的代码片段中还不清楚。
关于c - 将委托(delegate)编码到函数指针 : memory corrupt,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9940878/