【发布时间】:2020-08-26 12:19:39
【问题描述】:
我必须从 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 可能是问题,但试用代码不起作用。请帮我解决问题
【问题讨论】:
标签: c# c++ delegates marshalling unmanaged