How to pack given struct t1
in struct python
.
I see many examples are given here https://docs.python.org/2/library/struct.html to pack values like: pack('hhl', 1, 2, 3)
.
But how to pack the c type struct t1
in struct python
example.
struct s {
int16_t x;
int8_t y;
uint8_t z;
};
struct t1 {
int16_t x;
struct s y;
};
There doesn't seem to be builtin way to pack structs into structs, but you can do it manually. You pack the first struct into binary data, then pack that binary data into the second struct using the s
format character:
s= struct.Struct('hbB')
t1= struct.Struct('h{}s'.format(s.size))
buffer= t1.pack(1, s.pack(2,3,4))
And to unpack it:
loaded_t1= t1.unpack(buffer)
loaded_s= s.unpack(loaded_t1[1])
If i understand your question correctly, may be namedtuples could be used. Here is an example.
from collections import namedtuple
v1 = namedtuple("a1", "f1 f2");
var1 = v1(1, 2);
v2 = namedtuple("a2", "v1 f3");
var2 = (var1, 3);
Here is the output:
>>> print(var2)
(a1(f1=1, f2=2), 3)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.