Sub topic 13
Generating bindings with bindgen
This chapter assumes you can write extern blocks, use #[repr(C)] structs, and wrap raw calls in a safe API. It also assumes you have a Cargo project that compiles C with build.rs. Here you will let a tool write the declarations you have been typing by hand.
Why generate bindings
Hand-written declarations work for two functions. They do not scale to a header with 200 functions and dozens of structs. A wrong field type or a missing field in a #[repr(C)] struct compiles fine and corrupts memory at run time.
bindgen reads a C header and emits Rust extern declarations and #[repr(C)] types. The declarations come from the header itself, so they cannot drift from it.
Running bindgen from the command line
Install the command-line tool and point it at a header. This reuses the point.h header from the earlier chapter.
cargo install bindgen-cli
bindgen src/wrapper.h -o src/bindings.rsCreate src/wrapper.h as a small file that includes what you want bound:
/* src/wrapper.h */
#include "point.h"The generated file contains something like the following. The exact output varies by bindgen version.
#[repr(C)]
#[derive(Debug, Copy, Clone)]
pub struct point {
pub x: f64,
pub y: f64,
}
unsafe extern "C" {
pub fn point_distance(a: *const point, b: *const point) -> f64;
}Notice that the type is named point, copied from the C typedef. It is lowercase, so the Rust compiler will not complain here, but many C names will not follow Rust naming rules. Generated files usually start with #![allow(non_camel_case_types)] and similar attributes for this reason.
Running bindgen from build.rs
Checking in a generated file is simple, but it is tied to the platform and headers you generated it on. Many crates instead run bindgen at build time, so the output matches the headers on the build machine.
Add bindgen as a build dependency in Cargo.toml:
[build-dependencies]
cc = "1"
bindgen = "0.71"Then extend build.rs so it compiles the C file and generates the bindings:
use std::env;
use std::path::PathBuf;
fn main() {
cc::Build::new().file("src/point.c").compile("point");
let bindings = bindgen::Builder::default()
.header("src/wrapper.h")
.allowlist_function("point_.*")
.allowlist_type("point")
.generate()
.expect("failed to generate bindings");
let out = PathBuf::from(env::var("OUT_DIR").unwrap());
bindings
.write_to_file(out.join("bindings.rs"))
.expect("failed to write bindings");
println!("cargo:rerun-if-changed=src/wrapper.h");
println!("cargo:rerun-if-changed=src/point.h");
println!("cargo:rerun-if-changed=src/point.c");
}Cargo sets OUT_DIR to a build directory for the crate, so generated files stay out of your source tree. The allowlist_* calls limit the output to the names you need. Without them, bindgen also emits everything the header pulls in, such as items from system headers.
Include the generated file from src/lib.rs:
#![allow(non_camel_case_types, non_snake_case, non_upper_case_globals)]
#![allow(dead_code)]
mod ffi {
include!(concat!(env!("OUT_DIR"), "/bindings.rs"));
}
pub fn distance(a: (f64, f64), b: (f64, f64)) -> f64 {
let a = ffi::point { x: a.0, y: a.1 };
let b = ffi::point { x: b.0, y: b.1 };
unsafe { ffi::point_distance(&a, &b) }
}Keeping the generated code in a private module means callers only see your safe function.
Reviewing the output
bindgen is accurate about layout, but it cannot know the rules a C API leaves in comments. Read the generated code with these questions in mind.
- Pointer mutability. A
char *parameter becomes*mut c_char, even if the function only reads it. Check the documentation. - Ownership. bindgen cannot tell which functions return memory you must free. Wrap these in a
Droptype as in the earlier chapter. - Nullability. Every pointer is raw. Decide which ones may be null and expose
OptionorNonNullin your safe API. - Error conventions. Status codes appear as plain integers. Convert them to
Result. - Macros. Simple constants become Rust constants. Function-like macros are not translated.
Callbacks and enums deserve a second look. Rust enums generated for C enums can be undefined behavior if C returns a value that is not a listed variant, so bindgen defaults to integer constants. Keep that default unless you control the C side.
Common mistakes
| Problem | Cause | Fix |
|---|---|---|
| `fatal error: 'stdio.h' file not found` | libclang cannot find system headers | Install clang, or set `BINDGEN_EXTRA_CLANG_ARGS` |
| Huge bindings file | No allowlist, so system headers are included | Use `allowlist_function` and `allowlist_type` |
| Stale bindings after a header edit | Missing `rerun-if-changed` | Add a line for every header |
| Compile error on another platform | Checked-in file generated elsewhere | Generate in `build.rs` instead |
Exercise
Why does the build script above call allowlistfunction and allowlisttype, and what happens if you remove them?
Show answer
The allowlist limits bindgen's output to the items you name. Without it, bindgen generates declarations for everything reachable from the header, including types and functions from system headers. The result is a much larger file that is slower to compile and harder to review, though it still works.
Exercise
A generated declaration is pub fn name_set(obj: *mut thing, name: *mut c_char);. The C documentation says the function only reads name. Name two things you would check or change when writing the safe wrapper.
Show answer
Accept a &CStr and pass as_ptr() cast to *mut c_char only if the C function truly never writes through it, and confirm in the documentation that the function copies the string rather than keeping the pointer. Also take &mut self for the object, and make sure the object pointer is non-null, for example by holding it in a NonNull.