Hotcan

享受生活的点点滴滴

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

前一段时间遇到要使用C#调用一个dll的情况,其中有个回调函数,在C++里面的定义是这样的:

注册回调函数RegisterStreamDirectReadCallback
DLLEXPORT_API int __stdcall RegisterStreamDirectReadCallback(STREAM_DIRECT_READ_CALLBACK StreamDirectReadCallback,void *Context);

回调函数定义如下:
typedef int (*STREAM_DIRECT_READ_CALLBACK)(ULONG channelNumber,void *DataBuf,DWORD Length,int FrameType,void *context);

需要在C#里面通过Marshal实现这两个函数,对于第一个注册函数,定义如下:

[DllImport("DS40xxSDK.dll")]
public  static extern short RegisterStreamDirectReadCallback(STREAM_DIRECT_READ_CALLBACK StreamDirectReadCallback, IntPtr Context);        


回调函数用Delegate定义如下:

public unsafe delegate short STREAM_DIRECT_READ_CALLBACK( uint channelNumber, void * DataBuf,uint Length,int FrameType,void * Context); 


然后实现函数定义如下:

public unsafe short StreamDirectReadCallback(uint channelNumber, void * DataBuf,uint Length,int frameType,void * Context){}


 最后调用的时候回调的确成功了,调用如下:

RegisterStreamDirectReadCallback(new STREAM_DIRECT_READ_CALLBACK (this.StreamDirectReadCallback ),new IntPtr (0));

但是当回调函数结束以后,报错,而且当前没有代码,所以没有办法调试,估计还是定义的问题,研究了蛮久,还是不行,最后发现有些东西C#花的时间太多,得不偿失,所以最后还是决定使用C++来实现了。不过这个问题我还是想研究清楚,到底为啥呢?

关于void *尝试过IntPtr,也尝试过unsafe,总之都是不行,可能是void * DataBuf的原因,返回的时候由于不知道这个参数的大小,找不到入口了,其他的回调函数因为参数简单,只有一个int或者一个dword,可以直接返回。这个Marshal还是要好好研究研究的。
posted on 2005-01-12 23:58  Hotcan  阅读(2227)  评论(9编辑  收藏  举报