个人项目中,发现在发送不定长的报文数据的时候,所定义的结构体前部格式、长度等都固定。
除协议包外的body 内容,不固定。这里就可以在结构体内定义一个柔性数组。
该数组不占用结构体空间。
在发送报文的时候,可以让结构体指向数组。也可以malloc 固定的空间进行报文的发送。
typedef struct
{
uint8_t type;
uint8_t subType;
uint8_t devId[DEVICE_ID_LEN];
uint8_t dir;
uint8_t seqNo[SEQUENCE_NUMBER_LEN];
uint8_t bodyLen[BODYLEN_LEN];
uint8_t body[1];
}AppPkt_t;
{
uint8_t type;
uint8_t subType;
uint8_t devId[DEVICE_ID_LEN];
uint8_t dir;
uint8_t seqNo[SEQUENCE_NUMBER_LEN];
uint8_t bodyLen[BODYLEN_LEN];
uint8_t body[1];
}AppPkt_t;
AppCmdRespBodyGetDoorPassword_t *respBody;
uint8_t respBuff[20];
uint8_t respLen;
/* 填充响应 */
memset(respBuff, 0, sizeof(respBuff));
respBody = (AppCmdRespBodyGetDoorPassword_t *)respBuff;
respBody->srcSeqNo[0] = (uint8_t)(serverSeqNo & 0xFF);
respBody->srcSeqNo[1] = (uint8_t)((serverSeqNo >> 8) & 0xFF);
uint8_t respBuff[20];
uint8_t respLen;
/* 填充响应 */
memset(respBuff, 0, sizeof(respBuff));
respBody = (AppCmdRespBodyGetDoorPassword_t *)respBuff;
respBody->srcSeqNo[0] = (uint8_t)(serverSeqNo & 0xFF);
respBody->srcSeqNo[1] = (uint8_t)((serverSeqNo >> 8) & 0xFF);
PosdevAppPktBuff_t *appPktBuf;
appPktBuf = (PosdevAppPktBuff_t *)COS_MALLOC(sizeof(PosdevAppPktBuff_t) +
sizeof(PosdevAppPktHdr_t) +
bodyLen +
FRAME_CRC_LEN);
if (NULL == appPktBuf)
{
return -1;
}
appPktBuf = (PosdevAppPktBuff_t *)COS_MALLOC(sizeof(PosdevAppPktBuff_t) +
sizeof(PosdevAppPktHdr_t) +
bodyLen +
FRAME_CRC_LEN);
if (NULL == appPktBuf)
{
return -1;
}