Skip to content

Overview

Model common structs

Start here for the everyday building blocks of a CModel definition. This guide covers scalar fields, nested models, fixed-size repeated values, and fixed-length byte strings, then shows how to round-trip a model through bytes to confirm the layout.

Read this page first if you are still translating a C struct into Python and want a practical baseline before worrying about alignment details.

Control alignment and layout

Use this guide when field order alone is not enough and the exact byte layout matters. It explains how c_alignment affects padding, how packed structs differ from aligned structs, and how byte order remains a separate decision made at pack and unpack time.

Read this page when you are matching an existing binary protocol, file format, or ABI boundary and need confidence that the bytes land in the right positions.

Model tagged unions

Use this guide when a binary protocol or file format sends one of several possible message layouts, identified by a shared tag field. It shows how to define variant models, combine them with a Pydantic discriminator, and pack or unpack the correct variant automatically.

Read this page when the wire format includes a type tag that determines which struct layout follows.

Define custom field formats

Use this guide when the built-in aliases from cmodel.types do not fully describe a field. It shows how to define a CFormat, adapt raw binary values into richer Python values, and keep custom formats reusable without blurring the boundary between field format and struct layout.

Read this page when the structure is straightforward but one or two fields need a more specialized binary representation.

Define custom field encoders

Use this guide when a field needs custom or variable-length binary encoding that cannot be expressed as a struct format string. It shows how to define a CEncoded annotation with your own pack and unpack functions, and when to prefer it over CFormat.

Read this page when you need full control over how a field is read from and written to a binary buffer.

Reading path

If you are new to CModel, read these guides in order. If you already have a C struct or wire format in hand, jump directly to the guide that matches the layout problem you are solving.