使用 C# 将委托传递给非托管代码中的回调函数
Passing a Delegate to a callback function in unmanaged code using c#
我必须注册一个用 c# 的非托管代码编写的回调函数。我写了以下代码:
//Declaration for c++ code
[DllImport("sdk.dll")]
public static extern void sdkSetDequeueCallback(DequeueCallback cbfunc);
//call back delegate
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public delegate void DequeueCallback(OutData data);
GCHandle dequeueCallbackPinHandle;
Deque = new DequeueCallback(CallBackMethod);
{//try out
// Getting error following line (1 line) , Error : Object contains non-primitive or non-blittable data.
//dequeueCallbackPinHandle = GCHandle.Alloc(Deque, GCHandleType.Pinned);
//GC.KeepAlive(Deque);
}
SetDequeueCallback(Deque);
//Call back method in c#
public async void CallBackMethod(OutData data)
{}
以上代码在没有试用块的情况下也能正常工作,但问题是应用程序在一段随机时间(有时是 30 分钟、1 小时、8 小时等)后停止。在 try..catch 块中未检测到错误,但从 Windows 事件日志(应用程序)中获取以下 NullReferenceException 错误:
说明:进程因未处理的异常而终止。
异常信息:System.NullReferenceException。我认为
this
可能是问题,但试用代码不起作用。请帮我解决问题
您需要确保您的 'Deque' 引用存在并且不会被覆盖,只要在 C++ 中使用回调。只要使用相应的 C++ 回调,您就有责任保持委托 C# 对象处于活动状态。
更好的是,只需使用 Scapix Language Bridge, it generates C++ to C# bindings (including callbacks), completely automatically. Disclaimer: I am the author of Scapix Language Bridge。
我必须注册一个用 c# 的非托管代码编写的回调函数。我写了以下代码:
//Declaration for c++ code
[DllImport("sdk.dll")]
public static extern void sdkSetDequeueCallback(DequeueCallback cbfunc);
//call back delegate
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public delegate void DequeueCallback(OutData data);
GCHandle dequeueCallbackPinHandle;
Deque = new DequeueCallback(CallBackMethod);
{//try out
// Getting error following line (1 line) , Error : Object contains non-primitive or non-blittable data.
//dequeueCallbackPinHandle = GCHandle.Alloc(Deque, GCHandleType.Pinned);
//GC.KeepAlive(Deque);
}
SetDequeueCallback(Deque);
//Call back method in c#
public async void CallBackMethod(OutData data)
{}
以上代码在没有试用块的情况下也能正常工作,但问题是应用程序在一段随机时间(有时是 30 分钟、1 小时、8 小时等)后停止。在 try..catch 块中未检测到错误,但从 Windows 事件日志(应用程序)中获取以下 NullReferenceException 错误: 说明:进程因未处理的异常而终止。 异常信息:System.NullReferenceException。我认为 this 可能是问题,但试用代码不起作用。请帮我解决问题
您需要确保您的 'Deque' 引用存在并且不会被覆盖,只要在 C++ 中使用回调。只要使用相应的 C++ 回调,您就有责任保持委托 C# 对象处于活动状态。
更好的是,只需使用 Scapix Language Bridge, it generates C++ to C# bindings (including callbacks), completely automatically. Disclaimer: I am the author of Scapix Language Bridge。