用VC写了一个DLL,里面有个回调函数,用来回调数据上来。
回调函数的参数是个结构体,因为传递的数据量比较大。
VC里的定义如下:
typedef struct
{
BYTE mName[512];
int mId;
//都是这两种类型的,比较多我就没有全部列出来,
}ST_CALLBACK;typedef void fnCallback(int lpObj,ST_CALLBACK* command);对应C#里的结构体定义应该是什么写的?
下面是我写的,
public struct ST_CALLBACK
{
public byte[] myName = new byte[512];
//这里报错error CS0573: 'CSharpSample.ST_CALLBACK.mName': cannot have instance field initializers in structs
//我用string 什么测试也不行,
public int mId;
};public delegate void fnCallback(int lpObj, ST_CALLBACK lParam); //定义委托函数类型
//实际实现
public static void SIPCallback(int lpObj, ST_CALLBACK lParam)
{
MessageBox.Show("Callback", "Information", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); }
回调函数的参数是个结构体,因为传递的数据量比较大。
VC里的定义如下:
typedef struct
{
BYTE mName[512];
int mId;
//都是这两种类型的,比较多我就没有全部列出来,
}ST_CALLBACK;typedef void fnCallback(int lpObj,ST_CALLBACK* command);对应C#里的结构体定义应该是什么写的?
下面是我写的,
public struct ST_CALLBACK
{
public byte[] myName = new byte[512];
//这里报错error CS0573: 'CSharpSample.ST_CALLBACK.mName': cannot have instance field initializers in structs
//我用string 什么测试也不行,
public int mId;
};public delegate void fnCallback(int lpObj, ST_CALLBACK lParam); //定义委托函数类型
//实际实现
public static void SIPCallback(int lpObj, ST_CALLBACK lParam)
{
MessageBox.Show("Callback", "Information", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); }
byte[] myName;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 512)]
byte[] myName;当 MarshalAsAttribute.Value 设置为 ByValArray 时,必须设置 SizeConst 以指示数组中的元素数。当需要区分字符串类型时,ArraySubType 字段可以选择包含数组元素的 UnmanagedType。此 UnmanagedType 只可用于作为结构中的字段的数组。
{
BYTE mName[512];
int mId;
//都是这两种类型的,比较多我就没有全部列出来,
}ST_CALLBACK;
转C#
[StructLayout(LayoutKind.Sequential)]public struct ST_CALLBACK
{
[MarshalAs(UnmanagedType.ByValArray,SizeConst = 512 )]
byte []mName = new byte[512];
int mId;
}
public struct ST_CALLBACK
{
[MarshalAs(UnmanagedType.ByValArray,SizeConst = 512)]
public byte[] mName;
public int mId;
}
另外ST_CALLBACK lParam应改为ref ST_CALLBACK lParam。
在.net下用C++在封装一层(a.dll),然后用C#调用.
把结构体之类的东西,写在dll中就行了.
C#给(a.dll)传递参数,回调的数据可用消息机制返回.