
SystemsGuide
Safe Rust Bindings for a C Library a Worked Example
A good binding is two crates. The sys crate mirrors the C header exactly, and the safe crate hides the pointers behind types that cannot be misused.
19 min read
Tag
4 posts

A good binding is two crates. The sys crate mirrors the C header exactly, and the safe crate hides the pointers behind types that cannot be misused.

Memory must be freed by the allocator that created it. At an FFI boundary that means every allocation travels with a matching free function on the same side.

To expose Rust to C, mark functions extern "C" with a stable name, build a staticlib or cdylib and let cbindgen write the header. The rules are about layout, ownership and panics.

Rust calls C through extern declarations that you write or generate. bindgen reads a header and produces them, leaving you to wrap the unsafe calls in a safe API.