我已经给出了一个结构数组:
typedef struct sRawMsg{
int a;
}sRawMsg;
sRawMsg RawMsg[10];首先,使用数据填充结构数组条目。然后将数据复制到作为2D数组给定的输出缓冲器中。
// sending buffer which allocates memory for the array struct
static unsigned char sendingBuffer[10][sizeof(sRawMsg)];
for(int i = 0; i < 10; ++i)
{
sRawMsg* pMsg = &(RawMsg[i]);
// data is now stored in the struct array @ pos i
...
// data from the struct entry is now saved in the output sending buffer
memcopy(&(sendingBuffer[i][0]), pMsg, sizeof(sRawMsg));
}所获得的输出缓冲器作为普通字节数组在无线连接上传输。因为我是C编程新手,所以我想问一下是否有更有效、更优雅、更安全的方法来处理结构数组数据。
发布于 2016-04-13 01:06:15
由于您在结构中没有任何填充(使用任何常规编译器,一个元素结构都没有填充),因此您可以简单地将
(unsigned char *)&RawMsg[0]作为发送函数的参数。
如果您要将数据转换为固定格式(例如网络顺序),或者如果您的结构包含元素之间具有填充的混合类型,或者如果您的结构包含指向字符串的指针(或其他指向数据的指针),则您必须更加努力-使用类似于您正在做的序列化。有了指向字符串的指针,您可能需要一个知道如何识别字符串长度的协议。一种这样的约定被称为TLV (Type, length, value)。另一个(复杂得多的)是ASN.1。或者,您可以使用诸如JSON或BSON之类的格式,或者谷歌的Protocol buffers。
https://stackoverflow.com/questions/36579490
复制相似问题