Dissect Cstruct

4.7 · active · verified Fri Apr 17

dissect-cstruct is a Python library from the Dissect project designed for parsing C-like structures from binary data. It allows users to define structures using Python classes or C-like syntax and then parse byte streams into accessible Python objects. The current version is 4.7, and it is actively maintained with a regular release cadence.

Common errors

Warnings

Install

Imports

Quickstart

This example demonstrates how to define a C-like structure using `typedef`, create a byte string, and then parse it into an accessible Python object using `dissect-cstruct`.

from dissect.cstruct import cstruct
import struct

# Initialize a cstruct context
ctx = cstruct()

# Define a C-like structure using a multiline string
ctx.typedef(
    """
    struct Header {
        uint32_t magic;
        uint16_t version;
        char name[10];
    };
    """
)

# Example binary data conforming to the structure
# magic = 0xDEADBEEF (little endian)
# version = 0x0100 (little endian)
# name = "TestHeader" (10 chars)
# Use struct.pack to ensure correct byte ordering for the example
example_data = struct.pack("<I H 10s", 0xDEADBEEF, 0x0100, b"TestHeader")

# Parse the data using the defined structure
parsed_header = ctx.Header(example_data)

# Access fields of the parsed structure
print(f"Magic: {hex(parsed_header.magic)}")
print(f"Version: {parsed_header.version}")
print(f"Name: {parsed_header.name.decode('ascii')}")

# Assertions to verify correct parsing
assert parsed_header.magic == 0xDEADBEEF
assert parsed_header.version == 0x0100
assert parsed_header.name == b"TestHeader"

print("Structure parsed successfully!")

view raw JSON →