我c#程序中
注册回调函数:public static extern int RegisterStreamDirectReadCallback_API(STREAM_DIRECT_READ_CALLBACK StreamDirectReadCallback,  IntPtr Context);
回调函数:[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
        public delegate int STREAM_DIRECT_READ_CALLBACK(uint channelNumber, IntPtr DataBuf, uint Length, int FrameType, IntPtr context);
开启录像函数:public static extern int StartVideoCapture_API(IntPtr hChannelHandle);
在程序中首先调用"注册回调函数"RegisterStreamDirectReadCallback_API(STREAM_DIRECT_READ_CALLBACK StreamDirectReadCallback,  IntPtr Context);,然后调用"开启录像函数"StartVideoCapture_API(IntPtr hChannelHandle);调用"开启录像函数"之后,只要收到数据系统就会通知"注册回调函数"对"回调函数"进行调用,但是现在我的程序中会随机的出现如下错误:
CallbackOnCollectedDelegate was detected
Message: A callback was made on a garbage collected delegate of type '预览api实验!预览api实验.Form1+STREAM_DIRECT_READ_CALLBACK::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.   

    那应该怎么避免让它回收啊,就是不太知道应该怎么解决,我看他说要启动什么MDA配置,可有不太懂怎么做.
      

  2.   

    to:hdt
    不知道您以前是否遇到过这样的情况,是怎么解决的啊!
      

  3.   

    注册回调函数:RegisterStreamDirectReadCallback_API(new STREAM_DIRECT_READ_CALLBACK(callback_STREAM_DIRECT_READ_CALLBACK),  this.Handle);
    回调函数:[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
            public delegate int STREAM_DIRECT_READ_CALLBACK(uint channelNumber, IntPtr DataBuf, uint Length, int FrameType, IntPtr context);
    开启录像函数: StartVideoCapture_API(channelnum[1]);
    回调函数体: public int callback_STREAM_DIRECT_READ_CALLBACK(uint channelNumber,IntPtr DataBuf, uint Length, int FrameType, IntPtr context)
            {
                ............................
                     函数执行体
               .................................
                return 0;
            }
    主要就是如何确保新new出来的委托实例callback_STREAM_DIRECT_READ_CALLBACK的生存期覆盖非托管代码的生存期,让委托不会在执行之前不会被垃圾回收.
      

  4.   

    http://community.csdn.net/Expert/topic/5072/5072411.xml?temp=.2770044
      

  5.   

    注意
    new delegate 的时间
      

  6.   

    我是现调用的:RegisterStreamDirectReadCallback_API(new STREAM_DIRECT_READ_CALLBACK(callback_STREAM_DIRECT_READ_CALLBACK),  this.Handle);然后调用StartVideoCapture_API(channelnum[1]);开启录像,收到数据的时候系统就会告诉RegisterStreamDirectReadCallback_API(new STREAM_DIRECT_READ_CALLBACK(callback_STREAM_DIRECT_READ_CALLBACK),  this.Handle);去回调新new出来的callback_STREAM_DIRECT_READ_CALLBACK,有的时候程序可以运行,有的时候就会出现新new出来的函数被垃圾回收的情况,现在就是想知道怎么样避免新new出来的callback_STREAM_DIRECT_READ_CALLBACK不被系统的垃圾回收机制自动回收.