[StructLayout(LayoutKind.Sequential, Pack = 1)]
public struct MessageBody
{
public UInt16 sync_tag;
public byte verson;
public UInt16 packet_length;
public byte payload_id;
[MarshalAs(UnmanagedType.ByValArray,SizeConst=20246)]
public byte[] payload_data;
public UInt16 crc16;
public void BuildBase(byte payloadId, byte[] structbody)
{
sync_tag = 0xAA * 256 + 0x55;
verson = 0x01;
payload_id = payloadId;
packet_length = clsConvert.IntToUint(BitConverter.GetBytes(sync_tag).Length + BitConverter.GetBytes(verson).Length + BitConverter.GetBytes(payload_id).Length + structbody.Length + BitConverter.GetBytes(crc16).Length);
payload_data = structbody;
}
}
现在我的struct是这样定义的,这样就写死了payload_data的长度,这样写是没有问题的。但是我的structbody动态传进来的,长度不一定。如果我不写[MarshalAs(UnmanagedType.ByValArray,SizeConst=20246)],后面struct转换成byte[]后校验CRC16的值每次都不一样,怎么办啊,求救啊。难道我得为每个不同长度struct类型定义一个struct??试遍百度方法,终究无解。struct包含byte[] struct动态
public struct MessageBody
{
public UInt16 sync_tag;
public byte verson;
public UInt16 packet_length;
public byte payload_id;
[MarshalAs(UnmanagedType.ByValArray,SizeConst=20246)]
public byte[] payload_data;
public UInt16 crc16;
public void BuildBase(byte payloadId, byte[] structbody)
{
sync_tag = 0xAA * 256 + 0x55;
verson = 0x01;
payload_id = payloadId;
packet_length = clsConvert.IntToUint(BitConverter.GetBytes(sync_tag).Length + BitConverter.GetBytes(verson).Length + BitConverter.GetBytes(payload_id).Length + structbody.Length + BitConverter.GetBytes(crc16).Length);
payload_data = structbody;
}
}
现在我的struct是这样定义的,这样就写死了payload_data的长度,这样写是没有问题的。但是我的structbody动态传进来的,长度不一定。如果我不写[MarshalAs(UnmanagedType.ByValArray,SizeConst=20246)],后面struct转换成byte[]后校验CRC16的值每次都不一样,怎么办啊,求救啊。难道我得为每个不同长度struct类型定义一个struct??试遍百度方法,终究无解。struct包含byte[] struct动态
解决方案 »
免费领取超大流量手机卡,每月29元包185G流量+100分钟通话, 中国电信官方发货