【问题标题】:Passing a Delegate to a callback function in unmanaged code using c#使用 c# 将委托传递给非托管代码中的回调函数
【发布时间】: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


    【解决方案1】:

    只要在 C++ 中使用回调,您就需要确保您的“双端队列”引用是活动的并且不会被覆盖。只要使用相应的 C++ 回调,您就有责任保持委托 C# 对象处于活动状态。

    更好的是,只需使用Scapix Language Bridge,它会完全自动生成 C++ 到 C# 的绑定(包括回调)。免责声明:我是Scapix Language Bridge的作者。

    【讨论】:

    • 我将对象设为静态并调用方法,现在它工作正常。
    猜你喜欢
    • 2011-02-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多