(Bear with me, I think in C and not Python, so you're probably about to see some real dumb stuff...)
I have many (100+) different C structs
, pulled into Python (version 3.5.1) as bytes
, that I want to be able to access using the original C struct's variable names. Here's a simple example. In Python I have received these bytes
:
# In Python:
example1_bytes = b'\x08\x09\x0a\x0b'
Assume these bytes
were provided by something running C, using a struct
of the following format:
// In C:
struct example1 {
uint8_t val1;
uint8_t val2;
uint8_t val3;
uint8_t val4; };
How can I process example1_bytes
so that I can access them like this:
# In Python:
result = process_example1_bytes(example1_bytes)
print(result.val1)
# Prints "8"
print(result.val2)
# Prints "9"
# Et cetera
Taking it a step further, what if the C struct
is more complex and contains arrays and/or sub-structs? For example, something like this:
// In C:
struct substruct {
uint8_t ss_val1;
uint8_t ss_val2; };
struct example2 {
uint8_t val1;
uint8_t val2;
struct substruct ss[8]; };
How can I process example2_bytes
so that I can access them like this:
# In Python:
result = process_example2_bytes(example2_bytes)
print(result.val1)
print(result.ss[3].ss_val2)
I've experimented a bit using Python's struct
unpack
, which returns tuples and I think is a step in the right direction, but it hasn't quite gotten me to the usable solution I want. I'm not sure if I need to go down the namedtuple
path or take some other direction.