C++中抓图回调函数
void (CALLBACK* DisplayCBFun)(long nPort,char * pBuf,long nSize,long nWidth,long nHeight,long nStamp,long nType,long nReceaved));
C#中定义为委托
public delegate void DisplayCBFun(int nPort, IntPtr pBuf, int nSize, int nWidth, int nHeight, int nStamp, int nType, int nReceaved);
C#中回调函数的实现
public void CB_DisplayCBFun(int nPort, IntPtr pBuf, int nSize, int nWidth, int nHeight, int nStamp, int nType, int nReceaved){ }
由于.Net的垃圾回收机制,因此在这类应用中,对委托进行垃圾回收后,委托再进行回调,将回引发CallbackOnCollectedDelegate异常。因此需要将委托声明为成员变量。
private DisplayCBFun dcbf;
private void Function()
{
dcbf = new DisplayCBFun(CB_DisplayCBFun);
HikPlayer.PlayM4_SetDisplayCallBack(nPort, dcbf);
}
private void Function()
{
dcbf = new DisplayCBFun(CB_DisplayCBFun);
HikPlayer.PlayM4_SetDisplayCallBack(nPort, dcbf);
}
然而我发现仍然会引发异常,很可能是频繁回调引发的。权威资料显示使用 GC.KeepAlive 来确保特定实例保持活动状态一段时间,能解决此问题。
private DisplayCBFun dcbf;
private void Function()
{
dcbf = new DisplayCBFun(CB_DisplayCBFun);
HikPlayer.PlayM4_SetDisplayCallBack(nPort, dcbf);
//解决方法
GC.KeepAlive(dcbf);
}
private void Function()
{
dcbf = new DisplayCBFun(CB_DisplayCBFun);
HikPlayer.PlayM4_SetDisplayCallBack(nPort, dcbf);
//解决方法
GC.KeepAlive(dcbf);
}
转载自:http://www.cnblogs.com/changyu/archive/2009/10/25/1589447.html 部分内容.