背景:主从机交互协议中,需要针对不同控制字封装回复消息接口。本文使用变长数组特性和零长数组特性对这类接口进行统一封装。
1 #pragma pack(1) 2 typedef struct { 3 uint8_t magic; 4 uint8_t len_H; 5 uint8_t len_L; 6 uint8_t cmd; 7 uint8_t data[0]; 8 } CmdType; 9 #pragma pack() 10 11 void SendCmd(uint8_t* data, int len) 12 { 13 for (int 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, int len) 20 { 21 uint8_t tx[sizeof(CmdType) + len]; 22 23 CmdType* cmd_ptr = (CmdType*)tx; 24 cmd_ptr->magic = 0x5A; 25 cmd_ptr->len_H = ((len + sizeof()) >> 8) & 0xff; 26 cmd_ptr->len_L = (len + 1) & 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 }
标签:C99,cmd,uint8,len,数组,CmdType,data,ptr,零长 From: https://www.cnblogs.com/TheShore/p/18332282