C#中用委托实现C++的回调函数


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);
}

然而我发现仍然会引发异常,很可能是频繁回调引发的。权威资料显示使用 GC.KeepAlive 来确保特定实例保持活动状态一段时间,能解决此问题。

private DisplayCBFun dcbf;
private void Function()
{
    dcbf = new DisplayCBFun(CB_DisplayCBFun);
    HikPlayer.PlayM4_SetDisplayCallBack(nPort, dcbf);
    //解决方法
    GC.KeepAlive(dcbf);
}

转载自:http://www.cnblogs.com/cyrix/articles/1771491.html 内容.


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM