在做C#与其它程序通信的系统时,往往会使用struc操作结构化的数据(如数据包等)。
本文简要提出一些使用思路,欢迎各位大牛赐教。
一、STRUCT结构设计
当数据的结构确定时,总结为下面两种情况:
1、数据长度确定(包括字符串):
此时可以直接利用struct来构造数据包,比如:
[StructLayout(LayoutKind.Sequential, Pack = 1)]
struct THeader
{
public short size;
public byte type;
public int seqno;
}
[StructLayout(LayoutKind.Sequential, Pack = 1, CharSet = CharSet.Ansi)]
struct TGSUpdateLadder
{
public THeader h;
public byte charlevel;
public uint charexplow;
public uint charexphigh;
public byte charclass;
public ushort charstatus;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 16)]
public string charname;
}