问题一
#define MAX_MSG_LEN //这个在C#中如何定义呢问题二
typedef struct
{
ushort u16SourceID;
ushort u16DestID;
short u16Length;
char u8MsgType;
char u8Padding;
}_MsgHeader;
typedef struct
{
_MsgHeader header; //结构体嵌套后,没有办法算字节
char u8MsgNum;
char u8FrameNum;
char u8LastFrame;
char u8HlPhlFlag;
ushort u16DataLength;
char u8Padding[2];
char u8Data[MAX_MSG_LEN]; 在C#中结构体无法定义数组量,这个怎么办
}MSG;
上面的MSG结构体没有办法用Marshal进行和byte数组转换。哪位有好主意。我这里别的没有,分很多;不够再发贴送。
#define MAX_MSG_LEN //这个在C#中如何定义呢问题二
typedef struct
{
ushort u16SourceID;
ushort u16DestID;
short u16Length;
char u8MsgType;
char u8Padding;
}_MsgHeader;
typedef struct
{
_MsgHeader header; //结构体嵌套后,没有办法算字节
char u8MsgNum;
char u8FrameNum;
char u8LastFrame;
char u8HlPhlFlag;
ushort u16DataLength;
char u8Padding[2];
char u8Data[MAX_MSG_LEN]; 在C#中结构体无法定义数组量,这个怎么办
}MSG;
上面的MSG结构体没有办法用Marshal进行和byte数组转换。哪位有好主意。我这里别的没有,分很多;不够再发贴送。
// compile with: /target:module
using System;
using System.Runtime.InteropServices;[StructLayout(LayoutKind.Sequential)]
public class LOGFONT
{
public const int LF_FACESIZE = 32;
public int lfHeight;
public int lfWidth;
public int lfEscapement;
public int lfOrientation;
public int lfWeight;
public byte lfItalic;
public byte lfUnderline;
public byte lfStrikeOut;
public byte lfCharSet;
public byte lfOutPrecision;
public byte lfClipPrecision;
public byte lfQuality;
public byte lfPitchAndFamily;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst=LF_FACESIZE)]
public string lfFaceName;
}看示例3中的对lfFaceName的处理,用MarshalAs属性的SizeConst可以定义数组的长度
C#中: const int MAX_MSG_LEN = 256;2, 你MSG中的header也不是指针。直接sizeof(MSG)就得到字节数char u8Data[MAX_MSG_LEN] 在C#中 可以 char[] u8Data;
它代表一个结构体,用sizeof算出来的是它的结构体大小。
不是指针的大小(指针都是int的;4个字节)
[StructLayout( LayoutKind.Sequential,Pack=1)]
struct _MsgHeader
{
ushort u16SourceID;
ushort u16DestID;
short u16Length;
char u8MsgType;
char u8Padding;
} [StructLayout(LayoutKind.Sequential, Pack = 1)]
struct MSG
{
const int MAX_MSG_LEN=2; _MsgHeader header;
char u8MsgNum;
char u8FrameNum;
char u8LastFrame;
char u8HlPhlFlag;
ushort u16DataLength;
[MarshalAs(UnmanagedType.ByValArray, SizeConst=2)]
char[] u8Padding;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = MAX_MSG_LEN)]
char[] u8Data;
public MSG(IntPtr ptr)
{
header = new _MsgHeader();
u8MsgNum = char.MinValue;
u8FrameNum = char.MinValue;
u8LastFrame = char.MinValue;
u8HlPhlFlag = char.MinValue;
u16DataLength = ushort.MinValue;
u8Padding = new char[1];
u8Data = new char[MAX_MSG_LEN];
}
}
的大小啊+上其他的大小。这样就没有办法用下面的方式转换 strut to byte[]
其实我想用下面的方法进行转换,来发网络字节流
static object BytesToStruct(byte[] bytes, Type strcutType)
{
int size = Marshal.SizeOf(strcutType);
IntPtr buffer = Marshal.AllocHGlobal(size);
try
{
Marshal.Copy(bytes, 0, buffer, size);
return Marshal.PtrToStructure(buffer, strcutType);
}
finally
{
Marshal.FreeHGlobal(buffer);
}
}