C ABI and bindgen

On this page

To enable mutual invocation between Rust and C, calling conventions, type layouts, and resource semantics must be aligned simultaneously. Function signatures can tell you that an argument is a pointer, but they usually cannot tell you how many elements it points to, how long it can be retained, who is responsible for freeing it, or whether callbacks might execute from other threads.

bindgen solves the automatic generation of declarations and layouts, while safe wrappers are responsible for translating external contracts into invariants that Rust can maintain. Simply marking generated functions as unsafe does not complete safe wrapping.

C Header Files and Build ConfigurationTarget ABI, macro definitions, field layouts, and exported symbols1Raw Rust Bindingsextern declarations, raw pointers, and C-compatible types2Manual Construction of Safe AbstractionsVerify length, ownership, lifetimes, threading, and error conventions3Safe Rust Callers4Safe FFI Wrapping: Signatures Are Only Part of the ContractInteract only through interfaces that maintain invariantsbindgen can generate declarations, but it cannot infer all semantics from pointer signatures.

Examining the Three Types of "Compatibility" Separately

extern "C" specifies the C calling convention for the target platform; repr(C) specifies the C layout rules for types such as structs; and C type aliases match the target platform's primitive types. The three do not replace each other.

C Interface TypeRust RepresentationVerification Needed
int, longcore::ffi::c_int, c_longUse target aliases; do not hardcode host width
size_tType generated by bindgen, often usizeTarget ABI and generation options
const char**const c_charIs it a NUL-terminated string or a length-prefixed byte buffer?
void**mut c_voidOwnership, actual object type, and nullability
Function pointer, possibly NULLOption<extern "C" fn(...)> etc.Parameters, return type, unsafe, and threading conventions
C enumCommonly integer types with constants or generated newtypesAll possible input values, not just named enum variants

Common 64-bit Unix systems use LP64, while 64-bit Windows uses LLP64, so the width of long differs. The solution is to match the actual C long; forcibly replacing it with i64 on Windows would directly break the declaration rather than fix portability.

repr(C) does not recursively change the default layout of internal field types; placing String or Vec into a repr(C) struct does not turn them into C-understandable containers. Field compatibility, alignment, packing, and compilation options must be checked together. The underlying type of C enums may also be affected by compiler options, and C can store integer values not defined by Rust enums; directly constructing invalid Rust discriminants results in undefined behavior. Rust Type Layout

A Complete bindgen Project

The following uses a C function that synchronously reads a byte slice to illustrate the contract. It does not retain the pointer; when n=0, it does not access p; when n>0, the caller must provide at least n readable bytes. The result is the bitwise XOR of all bytes.

Cargo.toml:

[package]
name = "ffi-demo"
version = "0.1.0"
edition = "2024"

[build-dependencies]
bindgen = "0.72"
cc = "1"

wrapper.h:

#ifndef DEMO_WRAPPER_H
#define DEMO_WRAPPER_H
#include <stddef.h>
#include <stdint.h>
uint8_t demo_xor(const uint8_t *p, size_t n);
#endif

demo.c:

#include "wrapper.h"
uint8_t demo_xor(const uint8_t *p, size_t n)
{
    uint8_t result = 0;
    for (size_t i = 0; i < n; ++i)
        result ^= p[i];
    return result;
}

build.rs:

use std::{env, path::PathBuf};

fn main() {
    println!("cargo:rerun-if-changed=wrapper.h");
    println!("cargo:rerun-if-changed=demo.c");
    cc::Build::new().file("demo.c").compile("demo");
    let bindings = bindgen::Builder::default()
        .header("wrapper.h")
        .allowlist_function("demo_xor")
        .parse_callbacks(Box::new(bindgen::CargoCallbacks::new()))
        .generate()
        .expect("generate bindings");
    bindings.write_to_file(
        PathBuf::from(env::var("OUT_DIR").expect("OUT_DIR"))
            .join("bindings.rs"),
    ).expect("write bindings");
}

src/main.rs:

mod raw {
    include!(concat!(env!("OUT_DIR"), "/bindings.rs"));
}

fn xor_bytes(bytes: &[u8]) -> u8 {
    // SAFETY: bytes are readable during the call; length is correct. C does not retain or modify the pointer,
    // does not dereference when length is zero, so a non-null pointer for an empty slice also satisfies this interface contract.
    unsafe { raw::demo_xor(bytes.as_ptr(), bytes.len()) }
}

fn main() {
    assert_eq!(xor_bytes(&[]), 0);
    assert_eq!(xor_bytes(&[1, 2, 3, 4]), 4);
    println!("FFI checks passed");
}

Running cargo run requires a C compiler and libclang used by bindgen. The cc build compiles and links the C implementation, while bindgen is only responsible for generating Rust declarations; simply including the generated file will not magically provide native function implementations. bindgen Build Tutorial

When cross-compiling, you must also ensure that Clang's target, sysroot, include paths, and macros match the settings used to actually compile the library. Successful generation only indicates that the header file can be parsed; it does not prove that the bindings and the deployed binary ABIs are consistent. For critical structures, compare sizeof, alignof, and field offsets on both ends.

Pointer Lifetimes and Ownership

CStr::from_ptr requires a valid NUL-terminated string; its scan range must be readable during the borrow period; it does not verify arbitrary raw addresses, nor does it prove that the bytes are UTF-8. CString, on the other hand, owns the C string allocated by Rust, and the borrow from as_ptr cannot exceed the object's lifetime.

Transferring resources across boundaries should provide paired protocols, such as create/destroy or Rust-allocated, Rust-exported free functions. Do not casually use C free to release Box/CString, nor call Vec::from_raw_parts on C memory that does not conform to Rust's allocation layout contract.

If C retains the pointer, temporary stack objects or borrows within a single function call are usually insufficient. An ownership object is needed to guarantee unregistration and wait for in-flight callbacks to complete before releasing; simply casting the address to usize does not extend the lifetime.

Wrapping create/destroy into a Non-Copyable Object

The synchronous slice example only borrows memory. If C returns long-term resources, you can hide the layout behind an opaque type, allowing Rust to access it only through functions. The following are the complete steps to extend the previous project: append the declarations before the #endif in wrapper.h.

typedef struct demo_counter demo_counter;
demo_counter *demo_counter_new(uint32_t initial);
uint32_t demo_counter_get(const demo_counter *p);
int demo_counter_add(demo_counter *p, uint32_t amount);
void demo_counter_free(demo_counter *p);

Append the implementation to demo.c. The teaching interface stipulates that the initial value cannot exceed 100; creation failure returns NULL; add overflow returns 1 and does not modify the original value; successful addition returns 0. The parameters for get/add must point to objects that are still alive.

#include <stdlib.h>
struct demo_counter { uint32_t value; };

demo_counter *demo_counter_new(uint32_t initial) {
    if (initial > 100) return NULL;
    demo_counter *p = malloc(sizeof *p);
    if (p) p->value = initial;
    return p;
}
uint32_t demo_counter_get(const demo_counter *p) {
    return p->value;
}
int demo_counter_add(demo_counter *p, uint32_t amount) {
    if (UINT32_MAX - p->value < amount) return 1;
    p->value += amount;
    return 0;
}
void demo_counter_free(demo_counter *p) {
    free(p);
}

In build.rs, change allowlist_function("demo_xor") to allowlist_function("demo_.*") so that the new functions also generate declarations; the required parameter types will be included as dependencies dictate. Then replace src/main.rs with the owning wrapper below. bindgen allowlist

demo_counter_newNULL: Rejected or allocation failedCounter(NonNull)Sole ownership, private fieldDropCalls C's free functionadd error: value unchangedOpaque Handle: Enters Owning State Only Upon Successful CreationStill owned and released by the same CounterNonNull only excludes NULL; valid objects, sole release rights, and threading rules still come from the interface contract.
use std::ptr::NonNull;
#[allow(non_camel_case_types)]
mod raw {
    include!(concat!(env!("OUT_DIR"), "/bindings.rs"));
}
struct Counter(NonNull<raw::demo_counter>);
impl Counter {
    fn new(initial: u32) -> Result<Self, &'static str> {
        // SAFETY: C interface accepts any u32, returning a newly allocated unique object on success.
        let pointer = unsafe { raw::demo_counter_new(initial) };
        NonNull::new(pointer).map(Self).ok_or("counter creation failed")
    }
    fn value(&self) -> u32 {
        // SAFETY: Private handle owned by self and not yet released; get does not modify the object.
        unsafe { raw::demo_counter_get(self.0.as_ptr()) }
    }
    fn add(&mut self, amount: u32) -> Result<(), &'static str> {
        // SAFETY: Exclusive access to valid handle; function does not retain pointer and does not modify value on failure.
        match unsafe { raw::demo_counter_add(self.0.as_ptr(), amount) } {
            0 => Ok(()),
            _ => Err("counter addition failed"),
        }
    }
}
impl Drop for Counter {
    fn drop(&mut self) {
        // SAFETY: Paired with C creation function, normal ownership path releases exactly once.
        unsafe { raw::demo_counter_free(self.0.as_ptr()) }
    }
}
fn main() {
    // SAFETY: C does not access pointer when length is zero, NULL conforms to demo_xor convention.
    assert_eq!(unsafe { raw::demo_xor(std::ptr::null(), 0) }, 0);
    assert!(Counter::new(101).is_err());
    let mut counter = Counter::new(10).expect("create counter");
    counter.add(5).unwrap();
    assert_eq!(counter.value(), 15);
    assert!(counter.add(u32::MAX).is_err());
    assert_eq!(counter.value(), 15);
    drop(counter);
}

The wrapper does not implement Clone, nor does it expose raw pointer constructors, preventing two owners from each releasing the same resource. &mut self expresses the update requirement to the Rust caller; if the original library modifies the object from other threads itself, additional synchronization contracts must be established; this signature alone is insufficient.

NonNull does not automatically implement Send/Sync, so this wrapper does not make unfounded promises about cross-thread usage. It also does not prove that the address is readable or that the object type is correct; the external guarantees from new are the source of validity. Drop handles normal scope exit and unwind paths; mem::forget or process termination may still fail to release resources, so memory safety cannot rely on "destruction always executes". NonNull

This creation interface merges "invalid initial value" and "allocation failure" into NULL, making it impossible for Rust to reliably reconstruct the error reason discarded by C. When distinction is needed, design status codes and output handle protocols from the C layer, rather than guessing specific reasons based on NULL.

Callbacks: Threading, Reentrancy, and Unregistration Are More Important Than Function Pointers

When registering callback + void* context, clarify four things: which threads invoke it, whether it is concurrent, whether it is reentrant, and whether it is guaranteed that there are no in-flight callbacks after unregistration returns. Then decide on the Rust side whether to wrap it using locks, atomics, thread restrictions, or other ownership structures.

Do not immediately construct &mut T just because the C signature lacks const. Exclusive references require satisfying Rust's aliasing and validity rules throughout the borrow period; external callback reentrancy or concurrent access may violate them. Rustonomicon FFI

Who can still access context after unregister?

Unregistering alone is not enough: under this protocol, a callback that entered earlier still has an access in progress. Try freeing context before it finishes to expose the remaining dependency. A real safe wrapper must establish both no new access and completion of the last existing access.

Preparing the visual
Who can still access context after unregister?

Stopping new callbacks and waiting for in-flight calls are both required; a function-pointer signature does not encode timing.

Panics and Cross-Language Unwinding

Ordinary extern "C" is an ABI that does not allow unwinding to cross boundaries. When a Rust panic attempts to cross such a boundary, the process terminates; it is incorrect to continue using the broad statement that "all Rust panics crossing C boundaries are necessarily UB." External exceptions entering Rust boundaries that do not allow unwinding carry a risk of undefined behavior.

If cross-boundary unwinding is indeed required, use C-unwind according to the support of both toolchains and establish an overall exception protocol. The more common practice for ordinary C library interfaces is to convert catchable panics into errors inside Rust callbacks, but catch_unwind only catches unwinding panics, cannot catch panic=abort, and is not a universal catcher for all external exceptions. Whether the data structure remains consistent after recovery is still the responsibility of the application. FFI Unwinding Rules

Rust 2024 requires external declarations to use unsafe extern blocks; exporting fixed symbol names uses corresponding syntax like #[unsafe(no_mangle)]. The unsafe attribute emphasizes global obligations such as name conflicts; it does not automatically add C calling conventions to functions. Rust External Blocks

Automatically Generated Boundaries

bindgen does not understand semantics between length parameters, promises to retain pointers, or threading constraints. Handling complex C++ templates and inline functions is also not simply "all unsupported": some scenarios can generate wrappers, handle specific instances, or compile additional auxiliary files, depending on options and limitations; complex C++ interfaces often benefit from first organizing a clear C interface layer. bindgen FAQ

The generation layer remains mechanical and reproducible; the safety layer records the external guarantees each unsafe block relies on, and prevents callers from breaking them through ordinary safe operations. For more contract reasoning, see unsafe soundness.