在Python中解压缩嵌套的C结构 [英] Unpacking nested C structs in Python
问题描述
我正在尝试解压缩以二进制形式传递给我的Python程序的C结构,其中包括另一个嵌套结构. C标头的相关部分如下所示:
I am trying to unpack a C struct that is handed to my Python program in binary form and includes another nested struct. The relevant part of the C header looks like this:
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;
现在,在我的Python程序中,我想使用struct.unpack
解压缩accpacket
.但是,我不知道解压缩的格式字符串应该是什么,因为accpacket
包含嵌套的mps_packet_header
.我试过只在开头插入mps_packet_header
的格式字符串,然后继续其余的accpacket
:
Now, in my Python program, I want to use struct.unpack
to unpack an accpacket
. However, I don't know what the format string for the unpack should be as the accpacket
contains a nested mps_packet_header
. I have tried just inserting the format string for the mps_packet_header
at the beginning and then continuing with the rest of the accpacket
:
s = struct.Struct('= B B H H 6h 6h 6h H')
seq, _type, flags, upTimestamp, x, y, z, lowTimestamp = s.unpack(packet_data)
但是,这显然是不正确的.格式字符串的calcsize
为44,而结构本身的大小为54.
However, this is apparently not correct; the format string has a calcsize
of 44, while the struct itself has a size of 54.
如何为该结构制定正确的格式字符串?
How do I formulate a correct format string for this struct?
推荐答案
- 您的
Struct
格式与C结构不匹配. (最终H
应该为6H
) - struct.unpack(
6h
,..)确实返回6个字段. (没有一个包含6个元素)
- You
Struct
format does not match with C structure. (finalH
should be6H
) - struct.unpack(
6h
, ..) does return 6 fields. (not one with 6 elements)
因此您的代码应类似于..
So your code should looks like ..
s = struct.Struct('= B B H H 6h 6h 6h 6H')
fields = s.unpack(packet_data)
seq, _type, flags, upTimestamp = fields[:4]
x = fields[4:10]
y = fields[10:16]
z = fields[16:22]
lowTimestamp = fields[22:]
这篇关于在Python中解压缩嵌套的C结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!