【发布时间】:2010-11-25 07:26:21
【问题描述】:
我通过 USB 将 64 字节数据包传递给微控制器。在微控制器 C 代码中,数据包具有以下结构,
typedef union
{
unsigned char data[CMD_SIZE];
cmd_get_t get;
// plus more union options
} cmd_t;
与
typedef struct
{
unsigned char cmd; //!< Command ID
unsigned char id; //!< Packet ID
unsigned char get_id; //!< Get identifier
unsigned char rfu[3]; //!< Reserved for future use
union
{
unsigned char data[58]; //!< Generic data
cmd_get_adc_t adc; //!< ADC data
// plus more union options
} data; //!< Response data
} cmd_get_t;
和
typedef struct
{
int16_t supply;
int16_t current[4];
} cmd_get_adc_t;
在 C# 的 PC 端,我提供了一个函数,该函数将 64 字节数据包作为 Byte[] 返回。该函数使用 Marshal.Copy 将接收到的数据复制到 Byte[] 数组中。然后我使用了一个 C# 结构体
[StructLayout(LayoutKind.Sequential, Pack=1)]
public struct COMMAND_GET_ADC
{
public byte CommandID;
public byte PacketID;
public byte GetID;
[MarshalAs(UnmanagedType.ByValArray, SizeConst=3)]
public byte[] RFU;
public short Supply;
[MarshalAs(UnmanagedType.ByValArray, SizeConst=4)]
public short[] Current;
}
并再次使用 Marshal.Copy 将字节数组复制到结构中,以便我可以将其用作结构化数据,例如
COMMAND_GET_ADC cmd = (COMMAND_GET_ADC)RawDeserialize(INBuffer, 1, typeof(COMMAND_GET_ADC));
short supply = cmd.Supply;
与
public static object RawDeserialize(Byte[] rawData, int position, Type anyType)
{
int rawsize = Marshal.SizeOf(anyType);
if(rawsize > rawData.Length)
{
return null;
}
IntPtr buffer = Marshal.AllocHGlobal(rawsize);
Marshal.Copy(rawData, position, buffer, rawsize);
object retobj = Marshal.PtrToStructure(buffer, anyType);
Marshal.FreeHGlobal(buffer);
return retobj;
}
这感觉就像我正在制作大量数据副本,并且好像它可能不是实现我想要的最有效的方式。我还需要将结构化数据转换回字节数组以向设备发送命令。我有一个使用相同过程的方法(即使用结构,然后将其序列化为字节数组并将字节数组传递给写入函数)。
还有更好的选择吗?
【问题讨论】: