如何使用Marshal转换字节数组中的Structure



我正在尝试使用Marshal将结构转换为字节数组。下面是我的代码片段

public struct DataFields
{
public byte return_code { get; set; }
public byte sw_rev_major { get; set; }
public byte sw_rev_minor { get; set; }
public byte writelock_radio_state { get; set; }
public byte protocol { get; set; }
public byte dev_revision { get; set; }
public byte mfg_id { get; set; }
public byte dev_type { get; set; }
public byte dev_function { get; set; }
public byte[] dev_model { get; set; }
public byte[] dev_tag { get; set; }
public void InitDataFields()
{
this.return_code = 0x00;
this.sw_rev_major = 0x01;
this.sw_rev_minor = 0x00;
this.writelock_radio_state = 0x20;
this.protocol = 0x02;
this.dev_revision = 0x01;
this.mfg_id = 0x1f;
this.dev_type = 0x4c;
this.dev_function = 0x03;
this.dev_model = new byte[] { 0x4d, 0x69, 0x63, 0x72, 0x6f, 0x20, 0x4d, 0x6f, 0x74, 0x69, 0x6f, 0x6e, 0x20, 0x34, 
0x37, 0x30, 0x30, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00
};
this.dev_tag = new byte[] { 0x46, 0x54, 0x2d, 0x31, 0x30, 0x31, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00
};
}
}
public static byte[] StructureToByteArray(DataFields str)
{
//Console.WriteLine($"parameter: {str}");
int size = Marshal.SizeOf(str);
//int size = 66;
Console.WriteLine($"marshal size: {size}");
byte[] arr = new byte[size];
IntPtr ptr = Marshal.AllocHGlobal(size);
Marshal.StructureToPtr(str, ptr, false);
Marshal.Copy(ptr, arr, 0, size);
//Marshal.DestroyStructure(ptr, typeof(T));
return arr;
}

当我执行代码时,StructureToByteArray((函数正在损坏dev_model和dev_tag的值。有人能帮忙找出这里出了什么问题吗?

这只是一个猜测,因为我不确定你真正想要的布局

[StructLayout(LayoutKind.Sequential)]
public struct DataFields
{
public byte return_code;
public byte sw_rev_major;
public byte sw_rev_minor;
public byte writelock_radio_state;
public byte protocol;
public byte dev_revision;
public byte mfg_id;
public byte dev_type;
public byte dev_function;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 25)]
public byte[] dev_model;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 32)]
public byte[] dev_tag;

}

最新更新