我正在尝试解压一个 C 结构,该结构以二进制形式传递给我的 Python 程序,并包含另一个嵌套结构。C 标头的相关部分如下所示:
typedef struct {
uint8_t seq;
uint8_t type;
uint16_t flags;
uint16_t upTimestamp;
}__attribute__ ((packed)) mps_packet_header;
typedef struct {
mps_packet_header header;
int16_t x[6];
int16_t y[6];
int16_t z[6];
uint16_t lowTimestamp[6];
}__attribute__((packed)) mps_acc_packet_t;
typedef mps_acc_packet_t accpacket_t;
Run Code Online (Sandbox Code Playgroud)
现在,在我的 Python 程序中,我想使用struct.unpack它来解压accpacket. 但是,我不知道解包的格式字符串应该是什么,因为它accpacket包含嵌套的mps_packet_header. 我尝试在开头插入格式字符串mps_packet_header,然后继续其余部分accpacket:
s = struct.Struct('= B B H H 6h 6h 6h H')
seq, _type, flags, upTimestamp, x, y, z, lowTimestamp = s.unpack(packet_data)
Run Code Online (Sandbox Code Playgroud)
然而,这显然是不正确的;格式字符串的大小为calcsize44,而结构体本身的大小为 54。 …
这是我上一个问题“在 Python 中解压嵌套 C 结构”的后续问题。我正在使用的结构变得更加复杂,我再次不确定如何完全解压和处理它们。
在C端,标头的相关部分如下所示:
typedef struct {
uint8_t seq;
uint8_t type;
uint16_t flags;
uint16_t upTimestamp;
}__attribute__ ((packed)) mps_packet_header;
typedef struct {
mps_packet_header header;
int16_t x[6];
int16_t y[6];
int16_t z[6];
uint16_t lowTimestmp[6];
}__attribute__ ((packed)) mps_acc_packet_t;
typedef mps_acc_packet_t accpacket_t;
typedef struct {
int16_t hb1;
int16_t hb2;
} acam_hb_data_set;
typedef struct __attribute__ ((packed)) {
mps_packet_header header;
uint16_t temp;
uint16_t lowTimestmp[8];
acam_hb_data_set dms_data[8];
} mps_dms_packet_t;
Run Code Online (Sandbox Code Playgroud)
由此产生了两个挑战。首先,我收到的数据包(以二进制形式)可以是mps_acc_packet_t或mps_dms_packet_t- 区分它们的唯一方法是读取两种数据包类型type所具有的字段mps_packet_header。这意味着我需要在知道数据包的完整内容之前将其解压,但我不知道如何干净地完成此操作,因为(如果我没有记错的话)这两种数据包类型有不同(calcsize分别为 54 和 56)。第二个挑战是解压mps_dms_packet_t …