当前位置:编程学习 > C#/ASP.NET >>

C#中如何将回调函数(callback)指针传给DLL?

请教高手,C#中如何将回调函数(callback)指针传给DLL? 具体地讲,我的问题是这样的:
DLL提供了这样一个函数:EnableCallback(FARPROC lpCallback), 而回调函数有这样的格式:
NotifyProcedure(byte sID, byte, pType, short address, short newValue); 我的实现如下:

[DllImport("modbusl.dll")]
public static extern bool EnableCallback([Out, MarshalAsAttribute(UnmanagedType.FunctionPtr)] PtrNotify lpCallback);

public delegate void PtrNotify(byte sID, byte pType, short address, short newValue);
public void NotifyProcedure(byte SlaveID, byte PointType, short Address, short NewValue)
{
    MessageBox.Show("Callback comes, Great!");
}

public void someFunc() 
{
    PtrNotify delPtr = new PtrNotify(NotifyProcedure);
    bool tcb = EnableCallback(delPtr);
}

开始运行时,它工作正常,DLL一回调,我的C#应用就显示“Callback comes, Great!” 但是或迟或早,回调就收不到了,而且一旦收不到, 如果DLL再调一次,C#窗口就消失了。我也曾用过Marshal.GetFunctionPointerForDelegate(),并辅之以垃圾回收:           
GCHandle gch = GCHandle.Alloc(delPtr);
GC.Collect();
bool tcb = EnableCallback(delPtr);
gch.Free();
没有多大改进,还是会发生回调收不到的情况。    

请教各路高手,问题出现在哪里?多谢!        --------------------编程问答-------------------- 应该是delPtr 被垃圾收集了吧。

GCHandle gch = GCHandle.Alloc(delPtr);
GC.Collect();
bool tcb = EnableCallback(delPtr);
gch.Free(); //这句必须在确定C/C++不再调用delPtr后才能调用。

建议将delPtr变成static的。这样最简单了。
--------------------编程问答-------------------- 加一句就应该能解决问题

GC.KeepAlive(delPtr);
--------------------编程问答-------------------- 学习... --------------------编程问答-------------------- --------------------编程问答-------------------- 1L说的对啊 --------------------编程问答-------------------- 我想一楼二楼都说得对,做了相应的改进后到现在为止我的程序工作正常。多谢!
只是有一点,不知道怎样将delPtr变成static, 如果用static PtrNotify delPtr通不过编译。不过,delPtr是否static似无关紧要,不是大问题。 --------------------编程问答-------------------- 很简单改动一下。
PtrNotify delPtr = new PtrNotify(NotifyProcedure);
这句挪到函数外面,成为成员变量即可。
当然了。你定义写函数外,使用时检查一下。


PtrNotify delPtr = null;
public void someFunc()  
{
  if(delPtr==null)delPtr = new PtrNotify(NotifyProcedure);
  bool tcb = EnableCallback(delPtr);
}
--------------------编程问答-------------------- C#的类方法应该是8字节吧,DELPHI的类方法是8字节。。你的DLL里面的全局函数回调类型的指针应该是4字节吧。。你赋值给它会出问题吧。。。。
补充:.NET技术 ,  C#
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,