我正在使用编组解析数据包,以下是我的代码
public class test_parsing
{
// TCP header packet
[StructLayout(LayoutKind.Explicit)]
struct COMP_PKT
{
[FieldOffset(0), MarshalAs(UnmanagedType.ByValArray, SizeConst = 12)]
public byte[] servername;
[FieldOffset(12), MarshalAs(UnmanagedType.ByValArray, SizeConst = 12)]
public byte[] serverpasswd;
[FieldOffset(24), MarshalAs(UnmanagedType.ByValArray, SizeConst = 4)]
public byte[] imei_tac;
[FieldOffset(28), MarshalAs(UnmanagedType.ByValArray, SizeConst = 3)]
public byte[] imei_msn;
[FieldOffset(31), MarshalAs(UnmanagedType.ByValArray, SizeConst = 2)]
public byte[] seq_number;
};
static private COMP_PKT fromByte(byte[] arr)
{
COMP_PKT str = new COMP_PKT();
GCHandle handle = GCHandle.Alloc(arr, GCHandleType.Pinned);
str = (COMP_PKT)Marshal.PtrToStructure(handle.AddrOfPinnedObject(), typeof(COMP_PKT));
handle.Free();
return str;
}
static private void Datapackparser(byte[] packet, int size, int indexno)
{
COMP_PKT comp_pkt_data = fromByte(packet);
char p = Convert.ToChar(packet[index+1]);
Console.WriteLine();
Console.WriteLine(Encoding.ASCII.GetString(comp_pkt_data.servername));
Console.WriteLine(Encoding.ASCII.GetString(comp_pkt_data.serverpasswd));
Console.WriteLine(Encoding.ASCII.GetString(comp_pkt_data.imei_tac));
Console.WriteLine(Encoding.ASCII.GetString(comp_pkt_data.imei_msn));
Console.ReadKey();
}
public static void Main()
{
byte[] temp = new byte[] { 112, 114, 97, 116, 121, 117, 115, 104, 0, 0, 0, 0, 112, 114, 97, 116, 101, 101, 107, 0, 0, 0, 0, 0, 49, 50, 51, 52, 49, 50, 51, 53, 54, 57, 57, 57, 57, 57 };
Datapackparser(temp, 1, 2);
}
}
我面临的问题是,如果我为imei_msn 保留SizeConst 偶数,则解析正确完成,但如果我为imei_msn 保留SizeConst 奇数,则显示以下错误“无法从程序集'test_paktparsing 加载类型'COMP_PKT',版本= 0.0。 0.0,Culture=neutral,PublicKeyToken=null',因为它在偏移 31 处包含一个对象字段,该字段未正确对齐或被非对象字段重叠。”
此外,如果我只解析到 imei_msn,那么 SizeConst 偶数或奇数都无关紧要,因为解析正确完成。那么我在哪里犯错了?