c# DLL调用CallbackOnCollectedDelegate错误


 public delegate int MFS100_CodeLineDelegate(int code, int docId, string codeline);
 public event MFS100_CodeLineDelegate MFS100_CodeLine;
 MFS100_CodeLineDelegate OnCodeline = new MFS100_CodeLineDelegate(MFS100_OnCodeLine);
 AdressCodeLine = Marshal.GetFunctionPointerForDelegate(OnCodeline);
 mfSetEvent((int)EventEnum.E_EVENT_CODELINE, AdressCodeLine.ToInt32());
 object cl = (object)AdressCodeLine;
 GC.KeepAlive(cl);
 [DllImport("mflib.dll")]
 public static extern int mfSetEvent(int eventID, int callsback);
 *Global variable*
 private static IntPtr AdressCodeLine;

我发送代理内存地址到dll设置设备,当我从dll得到回调时,我得到错误:"CallbackOnCollectedDelegate被检测到"。如何解决这个问题

GC.KeepAlive("your Delegate instance").

you could store your delegate instance on a global variable.
编辑1:

看一下下面的代码,你就会明白我是什么意思了
public class CallbackDemo
{
    //Don't forget to change the calling convention accordingly
    [UnmanagedFunctionPointer(CallingConvention.StdCall)]
    public delegate int MFS100_CodeLineDelegate(int code, int docId, string codeline);
    public event MFS100_CodeLineDelegate MFS100_CodeLine;
    //this is one method how you keep your delegate instance being collected by GC
    private readonly MFS100_CodeLineDelegate cache;
    public CallbackDemo()
    {
        cache = OnCallBack;
    }
    protected virtual int OnCallBack(int code,int docId,string codeline)
    {
        if(this.MFS100_CodeLine!=null)
        {
            MFS100_CodeLine(code, docId, codeline);
        }
        return 0;
    }
    [DllImport("mflib.dll")]
    private static extern int mfSetEvent(int eventID, MFS100_CodeLineDelegate callsback);
    private MFS100_CodeLineDelegate myDelegate;
    public void CallSetEvent(int eventId)
    {
        mfSetEvent(eventId, this.cache);
    }
}

您在错误的对象上调用KeepAlive - AddressCodeLine值的盒子副本。你想要保持存活的是委托对象本身,OnCodeline。

现在,KeepAlive只在方法返回之前保持对象的活动状态。如果回调委托可以异步调用,则应改为从字段引用委托。

相关内容

  • 没有找到相关文章

最新更新