pythoncbytepython-dataclasses

Reading C struct dumped into a file into Python Dataclass


Is there a consistent way of reading a c struct from a file back into a Python Dataclass?

E.g.

I have this c struct

struct boh {
  uint32_t a;
  int8_t b;
  boolean c;
};

And I want to read it's data into its own python Dataclass

@dataclass
class Boh:
  a: int
  b: int
  c: bool

Is there a way to decorate this class to make this somehow possible?

Note: for I've been reading bytes and offsetting them manually into the class when I'm creating it, I would like to know if there is a better option.


Solution

  • Since you already have the data read as bytes, you can use struct.unpack to unpack the bytes into a tuple, which can then be unpacked as arguments to your data class contructor. The formatting characters for struct.unpack can be found here, where L denotes an unsigned long, b denotes a signed char, and ? denotes a boolean:

    import struct
    from dataclasses import dataclass
    
    @dataclass
    class Boh:
        a: int
        b: int
        c: bool
    
    data = bytes((0xff, 0xff, 0xff, 0xff, 0x7f, 1))
    print(Boh(*struct.unpack('Lb?', data)))
    

    This outputs:

    Boh(a=4294967295, b=127, c=True)