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