Skip to main content

C-Dantic

Type-Safe Foreign Function Interface for Python (Pydantic + ctypes)

"It would’ve been a segfault, it’s now a Pydantic error."

C-Dantic is a production-grade safety layer that bridges Python's Pydantic data modeling with standard ctypes. It transforms the fragile "trust me" nature of FFI into a robust, validated, and ABI-faithful engineering discipline.

Born from Fire

C-Dantic was extracted from a high-stakes native integration for the pytron engine—an environment involving opaque handles, cross-thread callbacks, and sensitive memory layouts. In such environments, a single misaligned byte or an early-garbage-collected callback doesn't just throw an exception; it crashes the entire process.

C-Dantic places a Pydantic-powered protection at the Python-C boundary to stop these crashes before they happen.

Why C-Dantic?

  • Runtime Integrity: Pydantic validates data types before they touch C memory.
  • ABI Fidelity: Precise control over memory layout with __pack__ and __align__.
  • Execution Safety: Detects null pointers, symbol misses, and unbound libraries before they cause Access Violations.
  • Lifetime Management: Automatically pins Python callbacks to memory so they aren't garbage collected while the C side is still using them.
  • Modern Ergonomics: Use Annotated and standard type hints instead of arcane ctypes syntax.

Core Features

1. Type-Safe Structures (CStruct)

Define memory-mapped structures using Pydantic. Use Annotated to provide ABI-level representation.

from typing import Annotated
from cdantic import CStruct
import ctypes

class PackedData(CStruct):
    __pack__ = 1  # Force byte-alignment (Pragma Pack)
    id: Annotated[int, ctypes.c_byte]
    value: Annotated[int, ctypes.c_int]

# ABI Introspection
print(f"Size: {PackedData.sizeof()} bytes")      # Outputs: 5
print(f"Offset.id: {PackedData.offsetof('id')}") # Outputs: 0
print(f"Offset.val: {PackedData.offsetof('value')}") # Outputs: 1

2. Binding Safety (CFunction)

Define signatures on methods and enforce library binding. Calling a native function before the library is bound raises a descriptive LibraryNotBoundError instead of a crash.

from cdantic import CFunction, bind_library

class NativeEngine:
    @CFunction(func_name="webview_create")
    def create(self, debug: int, window: int) -> int: ...

engine = NativeEngine()
# engine.create(0, 0) -> Raises LibraryNotBoundError

bind_library(engine, "webview.dll")
engine.create(0, 0) # Now safe to call

3. Protected Callbacks (CCallback)

Convert Python functions to C-compatible pointers. C-Dantic automatically pins these callbacks to a global registry to prevent early garbage collection.

from cdantic import CCallback

@CCallback
def on_event(msg: str) -> int:
    print(f"Received: {msg}")
    return 1

4. Handle Ergonomics

Simplified NULL checks for pointers and opaque handles.

from cdantic import is_null, assert_not_null

handle = lib.create_entity()
if is_null(handle):
    logger.error("Failed to create entity")

# Or enforce with an exception
assert_not_null(handle, "EntityHandle") # Raises ValidationBoundaryError if NULL

The "Safety Shield" in Action

Without C-Dantic, this mistake crashes your interpreter:

# Raw ctypes would likely segfault here
lib.webview_create(debug="yes", window="oops") 

With C-Dantic, you get a clean, actionable validation report:

pydantic_core._pydantic_core.ValidationError: 2 validation errors for create
debug
  Input should be a valid integer [type=int_parsing, input_value='yes', input_type=str]
window
  Input should be a valid integer [type=int_parsing, input_value='oops', input_type=str]

Production Error Hierarchy

  • LibraryNotBoundError: Called a function before its library was loaded.
  • SymbolNotFoundError: Function name doesn't exist in the DLL/SO.
  • ValidationBoundaryError: Access Violations (e.g., NULL pointer dereference attempts).
  • CallbackLifetimeError: Callback GC protection failure.

Installation

pip install cdantic

License

MIT License.

Metadata

Release files for cdantic 0.1.9

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for cdantic 0.1.9
File Size Uploaded Provenance Actions
cdantic-0.1.9.tar.gz 11.0 kB With provenance Details for cdantic-0.1.9.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for cdantic 0.1.9
File Interpreter ABI Platform Actions
cdantic-0.1.9-py3-none-any.whl Python 3 none any Details for cdantic-0.1.9-py3-none-any.whl

Total release size: 18.6 kB

Release files / cdantic-0.1.9.tar.gz

Download URL cdantic-0.1.9.tar.gz
Size 11.0 kB
Tags Source
SHA-256 checksum
How to use checksums
ee5bbfe200d1fadfcccd9f69d753a64708e4ace45b7e8e1b74083851390787bd
BLAKE2b-256 checksum
How to use checksums
48a13bafd39d0d324c010a7da7e420e4d44a371fc9f2efce08e3e7ec9cb1805c
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/6.1.0 CPython/3.13.7

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Jan 17, 2026.

Transparency log

Release files / cdantic-0.1.9-py3-none-any.whl

Download URL cdantic-0.1.9-py3-none-any.whl
Size 7.7 kB
Tags Python 3
SHA-256 checksum
How to use checksums
9eb1c574a361069182741d4a79b1d58202e90adabca76af68a63a366dd5d2ef4
BLAKE2b-256 checksum
How to use checksums
d1635a91b9f1d0f74d90fd9b7538da28589348ff581bf4add1ecc06334ae6c81
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/6.1.0 CPython/3.13.7

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Jan 17, 2026.

Transparency log

Security for cdantic 0.1.9

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

Full provenance

Both files in this release have been uploaded with provenance metadata.

Select from 2 files

Attestation for cdantic-0.1.9.tar.gz

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Jan 17, 2026.

Transparency log

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

This release

0.1.9 This release

2 release files Full provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page