Skip to main content

Python package to translate C struct to classes

Project description

cstructimpl

A Python package for translating C structs into Python classes.

PyPI version License Python Versions


⚡ Quick Start

Install from PyPI:

pip install cstructimpl

Define your struct and parse raw bytes:

from cstructimpl import *


class Info(CStruct):
    age: Annotated[int, CType.U8]
    height: Annotated[int, CType.U8]


class Person(CStruct):
    info: Info
    name: Annotated[str, CStr(6)]


person = Person.c_build(bytes([18, 170]) + b"Pippo\x00")
print(person)  # Person(info=Info(age=18, height=170), name='Pippo')

🚀 Introduction

cstructimpl makes working with binary data in Python simple and intuitive.
By subclassing CStruct, you can define Python classes that map directly to C-style structs and parse raw bytes into fully typed objects.

No manual parsing, no boilerplate — just define your struct and let the library do the heavy lifting.


🔧 Type System

At the core of the library is the BaseType protocol, which defines how types behave in the C world:

class BaseType(Protocol[T]):

    def c_size(self) -> int: ...
    def c_align(self) -> int: ...
    def c_signed(self) -> bool: ...

    def c_build(
        self,
        raw: bytes,
        *,
        byteorder: Literal["little", "big"] = "little",
        signed: bool | None = None,
    ) -> T | None: ...

Any class that follows this protocol can act as a BaseType, controlling its own parsing, size, and alignment.

When parsing a struct:

  • If a field type is itself a BaseType, parsing happens automatically.
  • Otherwise, annotate the field with Annotated[..., BaseType] to tell the parser how to interpret it.

The library comes with a set of ready-to-use type definitions that cover the majority of C primitive types.


📌 Examples

Here are a few practical examples showing how cstructimpl works in real-world scenarios.

Basic Struct

Define a simple struct with two fields:

class Point(CStruct):
    x: Annotated[int, CType.U8]
    y: Annotated[int, CType.U8]


assert Point.c_size() == 2
assert Point.c_align() == 1
assert Point.c_build(bytes([1, 2])) == Point(1, 2)

Nested Structs

You can embed structs inside other structs:

class Dimensions(CStruct):
    width: Annotated[int, CType.U8]
    height: Annotated[int, CType.U8]


class Rectangle(CStruct):
    id: Annotated[int, CType.U16]
    dims: Dimensions


assert Rectangle.c_size() == 4
assert Rectangle.c_align() == 2
assert Rectangle.c_build(bytes([1, 0, 2, 3])) == Rectangle(1, Dimensions(2, 3))

Strings in Structs

Support for C-style null-terminated strings:

class Message(CStruct):
    length: Annotated[int, CType.U16]
    text: Annotated[str, CStr(5)]


raw = bytes([5, 0]) + b"Helo\x00"
assert Message.c_build(raw) == Message(5, "Helo")

Enums with Autocast

Automatically cast numeric values into Python Enums:

class Mood(Enum):
    HAPPY = 0
    SAD = 1


class Person(CStruct):
    age: Annotated[int, CType.U16]
    mood: Annotated[Mood, CType.U8, Autocast()]


raw = bytes([18, 0, 1, 0])
assert Person.c_build(raw) == Person(18, Mood.SAD)

Arrays of Structs

Define fixed-size arrays of structs inside another struct:

class Item(CStruct, align=2):
    a: Annotated[int, CType.U8]
    b: Annotated[int, CType.U8]
    c: Annotated[int, CType.U8]


class ItemList(CStruct):
    items: Annotated[list[Item], CArray(Item, 3)]


data = bytes(range(1, 13))  # 3 items × 4 bytes each
parsed = ItemList.c_build(data)

assert parsed == ItemList([
    Item(1, 2, 3),
    Item(5, 6, 7),
    Item(9, 10, 11),
])

🎭 Autocast

Sometimes raw numeric values carry semantic meaning. In C, this is usually handled with enums.
With cstructimpl, you can automatically reinterpret values into enums (or other types) using Autocast.

from cstructimpl import *


class ResultType(Enum):
    OK = 0
    ERROR = 1


class Person(CStruct):
    kind: Annotated[ResultType, CType.U8, Autocast()]
    error_code: Annotated[int, CType.I32]

This is equivalent to writing a custom builder:

from cstructimpl import *


class ResultType(Enum):
    OK = 0
    ERROR = 1


class Person(CStruct):
    kind: Annotated[ResultType, CBuilder(CType.U8, lambda u8: ResultType(u8))]
    error_code: Annotated[int, CType.I32]

But much simpler and less error-prone.


✨ Features

  • Define Python classes that map directly to C structs
  • Parse raw bytes into typed objects with a single method call
  • Built-in type system for common C primitives
  • Support for nested structs
  • Flexible extension via the BaseType protocol

📖 Use Cases

  • Parsing binary network protocols
  • Working with binary file formats
  • Interfacing with C libraries and data structures
  • Replacing boilerplate parsing code with clean, type-safe classes

📚 Documentation

More detailed usage examples and advanced topics are available in the documentation.


🤝 Contributing

Contributions are welcome!

If you'd like to improve cstructimpl, please open an issue or submit a pull request on GitHub.


📜 License

This project is licensed under the terms of the Apache-2.0 License.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

cstructimpl-0.3.0.tar.gz (12.0 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

cstructimpl-0.3.0-py3-none-any.whl (14.5 kB view details)

Uploaded Python 3

File details

Details for the file cstructimpl-0.3.0.tar.gz.

File metadata

  • Download URL: cstructimpl-0.3.0.tar.gz
  • Upload date:
  • Size: 12.0 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.13.7

File hashes

Hashes for cstructimpl-0.3.0.tar.gz
Algorithm Hash digest
SHA256 a8466e5d954fb7418984ad0d2d22212198f1e816c39e907cc731e5e93aa12b17
MD5 3c6c606ddaed82964149104548ffcab6
BLAKE2b-256 3a15fba1e0b4a0a7a1a96228d4b1bdb01f15bc5591e836cc09c52e9d9c2e29ee

See more details on using hashes here.

File details

Details for the file cstructimpl-0.3.0-py3-none-any.whl.

File metadata

  • Download URL: cstructimpl-0.3.0-py3-none-any.whl
  • Upload date:
  • Size: 14.5 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.13.7

File hashes

Hashes for cstructimpl-0.3.0-py3-none-any.whl
Algorithm Hash digest
SHA256 83fa3c7360a75f490c91c4dc2046d29e342cf1fbd68c6dc290e7e95fb130433b
MD5 8ac83149b30492fa30e325acb9b710b5
BLAKE2b-256 50fb8ac1f9754f241a750e62c540db6492d52ed15ba8a6cb2af4a6d424f660bd

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page