C++
public delegate bool EventCallBack(int index, int type, int param1, int param2); [DllImport(WAPA_DLL, EntryPoint = "WAPA_IPC_SetEventCallBack", CallingConvention = CallingConvention.Cdecl)] public static extern int WAPA_IPC_SetEventCallBack(EventCallBack fEvent);
C#调用
public ctlCamera() { InitializeComponent(); WAPAMethods.WAPA_IPC_Init(WAPAMethods.TVFORMAT.PAL); WAPAMethods.WAPA_IPC_SetEventCallBack(IpcOnEvent); } private bool IpcOnEvent(int index, int type, int param1, int param2) { var status = "未"; switch (type) { case 0: status = "断"; break; case 1: status = "断"; break; case 2: status = "移"; break; case 3: status = "警"; break; } Console.Write(string.Format("索引:{0},类型:{1},参数1:{2},参数2:{3}", index, type, param1, param2)); return true; }
出现错误: 对“XXX::Invoke”类型的已垃圾回收委托进行了回调。这可能会导致应用程序崩溃、损坏和数据丢失。向非托管代码传递委托时,托管应用程序必须让这些委托保持活动状态,直到确信不会再次调用它们。
解决方法:
将委托赋值给类中的成员,再调用此成员
private static WAPAMethods.EventCallBack eventCallBack; public ctlCamera() { InitializeComponent(); WAPAMethods.WAPA_IPC_Init(WAPAMethods.TVFORMAT.PAL); eventCallBack = IpcOnEvent; WAPAMethods.WAPA_IPC_SetEventCallBack(eventCallBack); }