使用C99 变长数组和和零长数组特性封装协议回复消息
背景:主从机交互协议中,需要针对不同控制字封装回复消息接口。本文使用变长数组特性和零长数组特性对这类接口进行统一封装。
1 #pragma pack(1) 2 typedef struct { 3 uint8_t magic; 4 uint8_t len_H; 5 uint8_t len_L; // data_len = sizeof(cmd) + sizeof(data) 6 uint8_t cmd; 7 uint8_t data[0]; // zero_size_array 8 } CmdType; 9 #pragma pack() 10 11 void SendCmd(uint8_t* data, int16_t len) 12 { 13 for (int16_t i = 0; i < len; i++) { 14 printf("%#x ", data[i]); 15 } 16 printf("\n"); 17 } 18 19 void ComandTrasmit(uint8_t cmd, uint8_t* data, int16_t len) 20 { 21 uint8_t tx[sizeof(CmdType) + len]; // vla 22 23 CmdType* cmd_ptr = (CmdType*)tx; 24 cmd_ptr->magic = 0x5A; 25 cmd_ptr->len_H = ((len + sizeof(cmd)) >> 8) & 0xff; 26 cmd_ptr->len_L = (len + sizeof(cmd)) & 0xff; 27 cmd_ptr->cmd = cmd; 28 if (len > 0) { 29 memcpy(cmd_ptr->data, data, len); 30 } 31 SendCmd(tx, sizeof(CmdType) + len); 32 }