public unsafe delegate int AlarmProc(int saddr, int daddr, int command, byte* data);public delegate void dAttachHandle(int saddr, int daddr, int command, byte[] data);
dAttachHandle te;
//启动监听
        public unsafe int StartAttch(int DeviceHandle,dAttachHandle AttachHandleFunction)
        {
            te = new dAttachHandle(AttachHandleFunction);
            AlarmProc ap = new AlarmProc(AttachHandleCS);
            return AttachHandle(DeviceHandle, ap);        }
        private unsafe int AttachHandleCS(int saddr, int daddr, int command, byte* data)
        {
            byte[] buffer = new byte[7];
            for (int i = 0; i < 7; i++)
                buffer[i] = data[i];
            te(saddr, daddr, command, buffer);
            return 0;        }错误信息:
A callback was made on a garbage collected delegate of type 'ACS.Reader!ACS.Reader.mmReader+AlarmProc::Invoke'. This may cause application crashes, corruption and data loss. When passing delegates to unmanaged code, they must be kept alive by the managed application until it is guaranteed that they will never be called.

解决方案 »

  1.   

    为什么一定要用unsafe块,直接写不行?
      

  2.   

    to Knight94(愚翁) 
       不用unsafe也是同样的错误。为什么回调会在垃圾回收里呢
      

  3.   

    to 不用unsafe也是同样的错误。为什么回调会在垃圾回收里呢如果你是为了dll使用,没必要用unsafe。
    如下试试
    public delegate int AlarmProc(int saddr, int daddr, int command, byte[] data);public delegate void dAttachHandle(int saddr, int daddr, int command, byte[] data);
    dAttachHandle te;//启动监听
    public int StartAttch(int DeviceHandle, dAttachHandle AttachHandleFunction)
    {
    te = AttachHandleFunction;

    AlarmProc ap = new AlarmProc(AttachHandleCS);
    return AttachHandle(DeviceHandle, ap);
    }private int AttachHandleCS(int saddr, int daddr, int command, byte[] data)
    {
    byte[] buffer = new byte[7];
    for (int i = 0; i < 7; i++)
    buffer[i] = data[i];
    te(saddr, daddr, command, buffer);
    return 0;
    }
      

  4.   

    非常感谢   Knight94(愚翁) 但是问题依旧
      

  5.   

    try
    AlarmProc ap = new AlarmProc(AttachHandleCS);
    定义为类成员变量