Leading a Rust team that wraps a C compression library, would you generate the bindings with bindgen or write them by hand, and where does the safe boundary go?
answer
- size and churn of the header
- libclang at build time
- raw layer, safe layer
- the reverse direction's header
basics
~20 sGenerate with bindgen when the header is large or changes, write by hand for a few stable functions. Either way, raw declarations sit in a thin sys layer, and a separate safe layer holds the unsafe calls, ownership and error mapping.
solid answer
~50 sIt depends on the surface, and the boundary matters more than the tool. **bindgen** reads the C header through libclang and emits `unsafe extern "C"` blocks, `#[repr(C)]` structs and constants that match the header exactly, plus layout assertions. That pays off for big or evolving headers and platform-dependent types, at the cost of a libclang dependency, or committed per-target output, and an allowlist to keep the output small. **Hand-written** declarations suit a handful of stable functions, and they let you mark obviously safe items `safe fn`, but every signature is an unchecked promise. Whichever you pick, put the raw items in a `-sys` crate or private module with no policy, and build a safe crate on top: owning types with `Drop`, `&CStr` and slices instead of raw pointers, `Result` instead of status codes, and the callback trampoline. For the reverse direction, **cbindgen** writes the C header from your Rust exports.
code
rust · 22 lines/* automatically generated by rust-bindgen 0.72.1 */
pub type kz_progress_fn = ::std::option::Option<
unsafe extern "C" fn(
ctx: *mut ::std::os::raw::c_void,
done: usize,
total: usize,
) -> ::std::os::raw::c_int,
>;
unsafe extern "C" {
pub fn kz_compress(
src: *const ::std::os::raw::c_uchar,
len: usize,
out: *mut *mut ::std::os::raw::c_uchar,
out_len: *mut usize,
progress: kz_progress_fn,
ctx: *mut ::std::os::raw::c_void,
) -> ::std::os::raw::c_int;
}
unsafe extern "C" {
pub fn kz_free(buf: *mut ::std::os::raw::c_uchar);
}go deeper
Recall what each tool does: bindgen turns a C header into Rust declarations, cbindgen turns Rust exports into a C header.
Explain what bindgen generates: unsafe extern blocks with implicitly unsafe functions, repr(C) structs, layout assertions. Say why hand-written declarations can drift silently.
Lay out the two-layer split, a raw sys layer and a safe layer with owning types, borrowed views, Result errors and trampolines, and where each SAFETY comment lives.
Weigh header size and churn, the platforms to support, libclang on build machines against committed output, and audit cost. Set the rule that application code depends only on the safe layer.
## The decision has two parts Wrapping a C library forces two separate choices that are often mixed up: 1. **How the raw declarations are produced**: generated by bindgen or written by hand. 2. **Where unsafe code stops**: which layer owns the raw pointers, the ownership rules and the error mapping, and what the rest of the codebase is allowed to see. The second choice decides soundness and maintainability. The first is mostly about cost and drift. ## Generated bindings with bindgen bindgen parses the header with **libclang**, the C compiler front end, so it sees the header the way a C compiler does: includes expanded, typedefs followed, the target's real type sizes. Simple constant macros become Rust constants; function-like macros are not translated. For the compression header it emits one `unsafe extern "C"` block per function, each function a plain `pub fn` (implicitly unsafe to call), and the callback typedef becomes `Option<unsafe extern "C" fn(...)>`, so null maps to `None`. | Factor | bindgen | Hand-written | |---|---|---| | Fidelity to the header | exact, re-derived on every run | only as good as the last review | | Layout safety | layout assertions generated by default (`layout_tests`) | you write `size_of` checks yourself | | Platform differences (`long`, enums, packing) | resolved per target by clang | easy to get wrong on one target | | Build dependency | libclang on every build machine, or pre-generated files per target | none | | Output size | everything the header pulls in unless you use `allowlist_function`, `allowlist_type`, `allowlist_var` | only what you need | | Safety qualifiers | every function unsafe; no `safe fn` | you can mark obviously safe items `safe fn` | Two ways to run bindgen are common: - **At build time** from a build script. This always matches the installed header, but every build machine needs libclang. Wiring that up is a build-configuration subject. - **Ahead of time**, committing the generated file per supported target and regenerating it when the C library is upgraded. Builds stay simple, and the diff in review shows exactly what changed in the C API. ## Hand-written bindings For a library with a handful of stable functions, hand-written declarations are reasonable. They are short and readable, need no extra tooling, and you can declare `safe fn kz_version() -> c_uint` so it needs no unsafe block. The risk is silent drift. When the C side changes a parameter from `int` to `size_t`, nothing breaks at compile or link time and the program has undefined behaviour. Mitigations: - a test that compiles the real header and checks sizes and constants; - pinning the C library version and reviewing its changelog; - switching to bindgen once the surface grows past what one person can audit. ## Where the safe boundary goes The widely used convention splits the work into two layers: 1. **Raw layer** (a `foo-sys` crate or a private module): only the extern declarations, `#[repr(C)]` types and constants, plus the linking setup, which is a Cargo subject. No policy and no safe functions. Everything stays as unsafe as the C API. 2. **Safe layer** (the `foo` crate): the only place that calls the raw functions. It provides: - **owning types** such as `KzBuffer` and `Compressor`, whose `Drop` calls the library's free function exactly once; - **borrowed views**: `&[u8]` and `&CStr` with lifetimes tied to their owner instead of raw pointers; - **`Result` errors** mapped from status codes, with the library's message copied out through `CStr`; - **callback trampolines** that catch panics and recover closures from `void *ctx`; - **`Send` and `Sync` decisions** based on the C library's documented thread-safety, which the threads material covers. Every `unsafe` block sits in the safe layer with a `SAFETY` comment naming the C contract it upholds. Application code depends only on the safe crate, and can forbid unsafe code entirely. ## The reverse direction: cbindgen When Rust is the library and C is the host, **cbindgen** writes the header from your `extern "C"` + `#[unsafe(no_mangle)]` functions and `#[repr(C)]` types. Its documentation states that a type with a guaranteed layout gets a full definition, while one without gets only a **forward declaration**, which is right for opaque handles. It also notes that cbindgen does not understand Rust's module system, so two types with the same name confuse it. A generated header checked into the repository, with CI failing when regeneration produces a diff, keeps the Rust exports and the C prototypes from drifting apart. ## How a lead would frame it - Small, stable, single-platform C API: hand-write it, add a size test, keep it in a private module. - Large, changing or multi-platform C API: use bindgen with an allowlist, choose build-time or committed output based on how many machines must have libclang, and wrap it in a separate safe crate. - Exporting Rust to C: use cbindgen, with the header under version control and checked in CI.
- Why does bindgen leave every C function unsafe even when it obviously takes only integers?bindgen sees the signature, not the behaviour. A function taking only an `int` may still read global state, require an earlier init call, or misbehave on some values. So it emits plain items in an `unsafe extern "C"` block, which are implicitly unsafe, and leaves judgement to the safe layer, which can wrap the call in a safe Rust function after checking the contract.
- What do bindgen's generated layout assertions protect against?They check that each generated struct's size, alignment and field offsets match what clang computed for the target. A wrong packing pragma, a different target or a hand-edited binding then fails the build instead of silently reading the wrong fields. bindgen generates them by default; `layout_tests(false)` turns them off.
- bindgen output is safe Rust, so the wrapper layer is optional.
- Hand-written bindings are checked against the header at link time.
- Put Drop impls and error mapping in the -sys crate.
- cbindgen emits full C definitions for every Rust struct.
- Running bindgen needs no extra tools on the build machine.