最近在研究C#调用C++ DLL时,使用回调函数时程序执行几次后出现错误:对“XXX::Invoke”类型的已垃圾回收委托进行了回调。这可能会导致应用程序崩溃、损坏和数据丢失。向非托管代码传递委托时,托管应用程序必须让这些委托保持活动状态,直到确信不会再次调用它们。
经过网上查找发现是使用委托时的问题,解决方法:委托赋值给类的成员。
原来:
//回调
[DllImport("HDCamGrabFace.dll", CharSet = CharSet.Ansi, CallingConvention = CallingConvention.Cdecl)]
private static extern void HD_CAMERA_SetCallBack(HDCam_CallBack pCallback, IntPtr pContext);
//
public delegate void HDCam_CallBack(IntPtr pContext, uint dwMsg, uint dwParam1, uint dwParam2, uint dwParam3, uint dwParam4);
public void CallBack(IntPtr pContext, uint dwMsg, uint dwParam1, uint dwParam2, uint dwParam3, uint dwParam4)
{}
//调用:
HD_CAMERA_SetCallBack(CallBack, pthis.Handle);
修改后:
//回调
[DllImport("HDCamGrabFace.dll", CharSet = CharSet.Ansi, CallingConvention = CallingConvention.Cdecl)]
private static extern void HD_CAMERA_SetCallBack(HDCam_CallBack pCallback, IntPtr pContext);
//
public delegate void HDCam_CallBack(IntPtr pContext, uint dwMsg, uint dwParam1, uint dwParam2, uint dwParam3, uint dwParam4);
// 在类中定义委托变量
public static HDCam_CallBack hd_call_delegate = null;
public void CallBack(IntPtr pContext, uint dwMsg, uint dwParam1, uint dwParam2, uint dwParam3, uint dwParam4)
{}
//调用:
hd_call_delegate = new HDCam_CallBack(CallBack);
HD_CAMERA_SetCallBack(hd_call_delegate, pthis.Handle);