2

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.

3
  • A lot depends on how the data is packed/aligned. The int8_t and boolean could be in consecutive bytes or separated by a few bytes. Commented Nov 7, 2024 at 8:07
  • I feel your question boils down to "How do I serialise and deserialise my data?", i.e. about serialisation. Did you search for that concept? Commented Nov 7, 2024 at 8:15
  • The only truly common serializable format these days is UTF-8 encoded text. Plain ASCII should work on any system 99.999% of us come across as well (and is really a subset of UTF-8). Commented Nov 7, 2024 at 8:19

1 Answer 1

1

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)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.