日期:2014-05-19  浏览次数:20854 次

C#写C++ dll的回调函数问题
C++写的bmpcodec.dll
typedef   int   (*TXYS_DataArriveHandler_t)(long   iImageFrameNo,   int   iPackNo,   int   iDataSize,   unsigned   char*   ucData);
//向DLL注册图像数据到达事件的处理函数,输入参数:fHandlerFunc:处理函数名
extern   "C "   _declspec(dllexport)   int     TXYS_RegDataArriveEventHandler(TXYS_DataArriveHandler_t   fHandlerFunc);

现在要在C#里调用,我是这样做的
public   delegate   int   TXYS_DataArriveHandler_t(long   iImageFrameNo,   int   iPackNo,   int   iDataSize,   char[]   ucData);
         
[DllImport( "bmpcodec.dll ")]
                static   extern   int   TXYS_RegDataArriveEventHandler(TXYS_DataArriveHandler_t   fHandlerFunc);   //注册数据到来

public   int   fDataArriveHandler(long   iImageFrameNo,   int   iPackNo,   int   iDataSize,   char[]   ucData)
                {
                                             
                        return   0;
                }
Form()
{
InitializeComponent();
                        TXYS_InitSystem();
                      TXYS_DataArriveHandler_t   dataArrive   =   new   TXYS_DataArriveHandler_t(this.fDataArriveHandler);
                        TXYS_RegDataArriveEventHandler(dataArrive);//注册回调函数
}

发现不行?谁能帮我下?

------解决方案--------------------
为了能用上原来的C++代码,只好研究下从C# 中调用DLL
首先必须要有一个声明,使用的是DllImport关键字:
包含DllImport所在的名字空间
using System.Runtime.InteropServices;
public class XXXX{

[DllImport(“MyDLL.dll ")]
public static extern int mySum (int a,int b);
}


[DllImport(“MyDLL.dll ")]
public static extern int mySum (int a,int b);
代码中DllImport关键字作用是告诉编译器入口点在哪里,并将打包函数捆绑在这个类中
在调用的时候
在类中的时候 直接  mySum(a,b);就可以了
在其他类中调用: XXXX. mySum(a,b);

[DllImport(“MyDLL.dll”)]在申明的时候还可以添加几个属性
[DllImport(“MyDLL.dll ", EntryPoint= " mySum ",CharSet=CharSet.Auto,CallingConvention=CallingConvention.StdCall)
]
EntryPoint: 指定要调用的 DLL 入口点。默认入口点名称是托管方法的名称 。
CharSet: 控制名称重整和封送 String 参数的方式 (默认是UNICODE)
CallingConvention指示入口点的函数调用约定(默认WINAPI)(上次报告讲过的)
SetLastError 指示被调用方在从属性化方法返回之前是否调用 SetLastError Win32 API 函数 (C#中默认false )


int 类型
[DllImport(“MyDLL.dll ")]
//返回个int 类型
public static extern int mySum (int a1,int b1);
//DLL中申明
extern “C” __declspec(dllexport) int WINAPI mySum(int a2,int b2)
{
//a2 b2不能改变a1 b1
//a2=..
//b2=...
return a+b;
}


//参数传递int 类型
public static extern int mySum (ref int a1,ref int b1);
//DLL中申明
extern “C” __declspec(dllexport) int WINAPI mySum(int *a2,int *b2)
{
//可以改变 a1, b1
*a2=...
*b2=...
return a+b;
}


DLL 需传入char *类型
[DllImport(“MyDLL.dll ")]
//传入值
public static extern int mySum (string astr1,string bstr1);
//DLL中申明
extern “C” __declspec(dllexport) int WINAPI mySum(char * astr2,char * bstr2)