cstruct

raw JSON →
6.2 verified Fri May 01 auth: no python

A Python library for defining and parsing C-style structs. Supports nested structs, arrays, strings, and variable-length fields. Version 6.2 works with Python 3.7+ and supports Python 3.14. Released under the MIT license, with active maintenance and periodic updates.

pip install cstruct
error TypeError: __struct__ must be a list of tuples
cause The __struct__ attribute is not properly defined as a list of (field_name, field_type) tuples.
fix
Define __struct__ as a list of tuples, e.g., __struct__ = [('x', 'int'), ('y', 'int')].
error AttributeError: 'bytes' object has no attribute 'decode'
cause Attempting to call .decode() on a bytes object that is not a string field; or using a Python string where bytes are expected.
fix
Ensure string fields are unpacked as strings (they are automatically decoded) and binary fields are handled as bytes.
error ValueError: unpack requires a buffer of 8 bytes
cause The buffer length does not match the expected struct size (e.g., packing two ints expects 8 bytes).
fix
Verify the buffer length matches the struct size (calculate using len(struct_instance)).
breaking In v6.0, access to Python class attributes in struct definitions was added. Prior versions did not support this; code relying on dynamic attribute access may need updates.
fix Ensure struct definitions use the __struct__ list format or check compatibility if using Python class attributes.
deprecated The use of setup.cfg is deprecated; v6.2 moved to pyproject.toml. If you were customizing build via setup.cfg, migrate to pyproject.toml.
fix Update your build configuration to use pyproject.toml instead of setup.cfg.
gotcha Strings in structs (e.g., 'char[10]') are packed as null-terminated byte strings. Mismatch in length or encoding can cause corruption.
fix Define string fields with explicit length, e.g., ('name', 'char[32]'), and ensure raw bytes are encoded/decoded correctly.

Defines a simple Point struct, packs values, and unpacks from bytes.

from cstruct import CStruct

# Define a struct matching the C definition:
# struct Point { int x; int y; };
class Point(CStruct):
    __struct__ = [
        ('x', 'int'),
        ('y', 'int'),
    ]

# Create an instance and pack
p = Point(x=10, y=20)
data = p.pack()
print(data.hex())

# Unpack from bytes
p2 = Point(data)
print(p2.x, p2.y)