c#编组甚至奇怪的大小

时间:2013-08-15 06:41:12

标签: c# marshalling

我正在使用编组解析数据包,以下是我的代码

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奇数,则会显示以下错误 "无法加载类型' COMP_PKT'来自assembly' test_paktparsing,Version = 0.0.0.0,Culture = neutral,PublicKeyToken = null'因为它包含偏移31处的对象字段,该字段被非对象字段错误地对齐或重叠。"

此外,如果我只解析imei_msn,那么SizeConst even或odd并不重要,因为解析正确完成。那么我在哪里弄错了?

0 个答案:

没有答案