CStruct

Bases: AbstractCStruct

Convert C struct definitions into Python classes.

Attributes:

Name Type Description
__struct__ str

definition of the struct (or union) in C syntax

__byte_order__ str

byte order, valid values are LITTLE_ENDIAN, BIG_ENDIAN, NATIVE_ORDER

__is_union__ bool

True for union definitions, False for struct definitions

__size__ int

size of the structure in bytes (flexible array member size is omitted)

__fields__ list

list of structure fields

__fields_types__ dict

dictionary mapping field names to types

Source code in cstruct/cstruct.py
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
class CStruct(AbstractCStruct):
    """
    Convert C struct definitions into Python classes.

    Attributes:
        __struct__ (str): definition of the struct (or union) in C syntax
        __byte_order__ (str): byte order, valid values are LITTLE_ENDIAN, BIG_ENDIAN, NATIVE_ORDER
        __is_union__ (bool): True for union definitions, False for struct definitions
        __size__ (int): size of the structure in bytes (flexible array member size is omitted)
        __fields__ (list): list of structure fields
        __fields_types__ (dict): dictionary mapping field names to types
    """

    def unpack_from(self, buffer: Optional[bytes], offset: int = 0, flexible_array_length: Optional[int] = None) -> bool:
        """
        Unpack bytes containing packed C structure data

        Args:
            buffer: bytes to be unpacked
            offset: optional buffer offset
            flexible_array_length: optional flexible array lenght (number of elements)
        """
        self.set_flexible_array_length(flexible_array_length)
        if buffer is None:
            buffer = CHAR_ZERO * self.size
        for field, field_type in self.__fields_types__.items():
            setattr(self, field, field_type.unpack_from(buffer, offset))
        return True

    def pack(self) -> bytes:
        """
        Pack the structure data into bytes

        Returns:
            bytes: The packed structure
        """
        result: List[bytes] = []
        for field, field_type in self.__fields_types__.items():
            if field_type.is_struct or field_type.is_union:
                if field_type.vlen == 1:  # single struct
                    v = getattr(self, field, field_type.ref())
                    v = v.pack()
                    result.append(v)
                else:  # multiple struct
                    values = getattr(self, field, [])
                    for j in range(0, field_type.vlen):
                        try:
                            v = values[j]
                        except KeyError:
                            v = field_type.ref()
                        v = v.pack()
                        result.append(v)
            else:
                data = getattr(self, field)
                result.append(field_type.pack(data))
        return bytes().join(result)

pack()

Pack the structure data into bytes

Returns:

Name Type Description
bytes bytes

The packed structure

Source code in cstruct/cstruct.py
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
def pack(self) -> bytes:
    """
    Pack the structure data into bytes

    Returns:
        bytes: The packed structure
    """
    result: List[bytes] = []
    for field, field_type in self.__fields_types__.items():
        if field_type.is_struct or field_type.is_union:
            if field_type.vlen == 1:  # single struct
                v = getattr(self, field, field_type.ref())
                v = v.pack()
                result.append(v)
            else:  # multiple struct
                values = getattr(self, field, [])
                for j in range(0, field_type.vlen):
                    try:
                        v = values[j]
                    except KeyError:
                        v = field_type.ref()
                    v = v.pack()
                    result.append(v)
        else:
            data = getattr(self, field)
            result.append(field_type.pack(data))
    return bytes().join(result)

unpack_from(buffer, offset=0, flexible_array_length=None)

Unpack bytes containing packed C structure data

Parameters:

Name Type Description Default
buffer Optional[bytes]

bytes to be unpacked

required
offset int

optional buffer offset

0
flexible_array_length Optional[int]

optional flexible array lenght (number of elements)

None
Source code in cstruct/cstruct.py
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
def unpack_from(self, buffer: Optional[bytes], offset: int = 0, flexible_array_length: Optional[int] = None) -> bool:
    """
    Unpack bytes containing packed C structure data

    Args:
        buffer: bytes to be unpacked
        offset: optional buffer offset
        flexible_array_length: optional flexible array lenght (number of elements)
    """
    self.set_flexible_array_length(flexible_array_length)
    if buffer is None:
        buffer = CHAR_ZERO * self.size
    for field, field_type in self.__fields_types__.items():
        setattr(self, field, field_type.unpack_from(buffer, offset))
    return True