Chapter 8: Rust-C Integration and Migration
The chapter introduction explains why integrating embedded Rust with existing C code requires care at the language boundary.
After this chapter you will be able to
- Rust-C boundary responsibility. Explain why an embedded Rust project may need to interact with C and why Rust’s safety guarantees do not automatically cover calls or memory shared across that boundary.
- Bidirectional embedded FFI. Explain that FFI lets Rust call C and lets C call Rust, often to integrate existing embedded components such as legacy libraries, vendor HALs, startup code, or RTOS kernels.
- Cross-language compatibility risks. Explain why matching and linking code is not enough for a reliable language boundary: calling conventions, data layout, and type representations must agree. Describe how Rust makes FFI explicit and unsafe by default so the developer must attend to the ABI, layouts, and signatures.
- External declarations and C ABI. Explain that `extern` declares a function or static variable outside Rust and specifies an ABI, usually `"C"`, so the declaration follows the target platform’s C calling convention and type layout.
- Trust in external declarations. Explain why an `unsafe extern` block is a promise about declarations the compiler cannot verify, and distinguish that from an individual item marked safe to call.
- Stable names for C linkage. Explain why an exported Rust function uses `#[unsafe(no_mangle)]`: it keeps the written symbol name so a C linker can resolve it, while overriding Rust’s normal name mangling.
- ABI interoperability contract. Explain that an ABI lets separately compiled code agree on calling conventions, data layout, and symbol names at the machine-code level.
- Cortex-M procedure call rules. Describe the PCS as the function-calling part of the ABI and trace where ordinary Cortex-M arguments and return values go, including 64-bit arguments, stack spillover, and the hard-float exception.
- Existing C code integration. Explain why embedded Rust projects may need to use existing C code and what Rust’s FFI enables at a high level.
- Module-scoped C naming lints. Explain why C identifiers can trigger Rust naming warnings and why the declarations and lint suppressions should be kept in one module rather than applied crate-wide.
- Target-matched scalar bindings. Explain that Rust and C scalar types in an FFI binding must have compatible sizes and alignments on the target. Describe why i32 matches C int on ARM Cortex-M and why core::ffi types are a portable choice.
- C-compatible struct layout. Explain why a Rust struct shared with C needs #[repr(C)] and what that attribute guarantees.
- Predictable enum representation. Explain why a plain #[repr(C)] Rust enum is not guaranteed to have a fixed size, and describe how Rust and C can agree on a fixed-width representation.
- Validation of C-supplied states. Explain why a fixed-width Rust enum is still unsafe for unchecked values supplied by C, and describe the integer-wrapper-and-check approach.
- Safe wrappers at FFI boundaries. Explain why foreign calls are unsafe by default and how a safe Rust wrapper confines the unsafe call while enforcing an input rule, such as passing only non-negative arguments to C's add().
- Direct linking of prebuilt libraries. Explain when to use #[link] for a prebuilt C static library, how its library name is written, and why the linker may also need a search directory.
- Build script C compilation. Describe how build.rs and the cc crate compile C source and link it during a normal Cargo build, and explain why the Rust declaration no longer needs #[link].
- C-facing Rust interface. Explain why calling Rust from an existing C project requires attention to the boundary between the languages. Describe the need for predictable symbol names, data types, and linking.
- C-callable Rust function exports. Explain why a Rust function called from C needs both `extern "C"` and `#[unsafe(no_mangle)]`, and distinguish their roles from `pub`.
- Immutable Rust globals in C. Explain why C should declare an exposed immutable Rust static as `const` and what can happen if it does not.
- Panic Handler in Static Libraries. Explain why this no_std static library includes a panic handler even though it has no main function.
- C Linkable Static Archive. Describe how Cargo is configured to produce the Rust library in a form a C program can link.
- Static Library Linker Selection. Explain how gcc is directed to find and select the Rust static library using -L and -l.
- Bare-Metal Firmware Link Requirements. Explain the roles of -T and -nostartfiles and why linking successfully without the specified bare-metal startup components does not yield flashable firmware.
- Unused Static Library Code Removal. Explain why the section enables compile-time function and data sections and link-time garbage collection when linking a Rust staticlib into C firmware.
- C-compatible error codes. Explain why a Rust function called from C returns integer error codes instead of exposing Result or Option, and describe the usual meanings of zero and negative values.
- Output pointer safety contract. Explain why an output parameter from C is taken as a checked raw pointer rather than a Rust mutable reference, and why the exported function is still declared unsafe.
- Panic-free division errors. Explain why checking only for a zero divisor is insufficient and how checked_div addresses the division failures without using a panic to report an error to C.
- Array Pointers and Lengths. Describe how a Rust slice is passed to a C function that expects an array pointer and length.
- NUL-Terminated C Strings. Distinguish Rust strings from C strings and explain how &CStr and C string literals help when passing text to C.
- Retained Pointer Lifetimes. Explain why a pointer passed for one C call must not be retained afterward and describe what to provide when C needs the data later.
- Callback registration and timing. Explain how a callback differs from an ordinary function call: code supplies a function in advance, and the receiving library calls it later when an event occurs.
- Rust to C callback flow. Trace the example from declaring the C functions in a Rust extern block through registering rust_callback() and triggering its invocation from C. Explain why the supplied callback is an extern "C" fn.
- Callback context pointer pattern. Explain how a C library accepts a generic context pointer alongside a callback, stores the two together, and returns the pointer unchanged on each callback.
- Rust callback trampoline flow. Trace the example from install() registering count_events() and a pointer to EVENT_COUNT through to the callback casting that returned pointer to an AtomicU32 pointer and incrementing the counter.
- Context pointer safety contract. Justify why converting the returned context pointer requires unsafe code and why count_events() is an unsafe extern "C" function.
- Automated Rust C interface maintenance. Explain why hand-maintained Rust–C bindings become difficult as projects grow, and distinguish what bindgen and cbindgen generate.
- Header-to-binding workflow. Describe how to collect the needed C headers, include them through one wrapper header, run bindgen, and bring the generated declarations into a Rust project behind safe wrapper functions.
- Matching the C ABI. Justify passing the embedded target to libclang and matching any ABI-affecting compiler flags to the flags actually used to build the C library, especially for enum sizing.
- Automated binding output. Explain how build.rs automates bindgen for repeatable builds and why generated bindings belong in Cargo’s OUT_DIR rather than src/.
- Including generated declarations. Trace how Rust finds the bindings file in OUT_DIR and brings its declarations into a named module.
- Generated call safety boundary. Explain how the module wrapper affects calls to generated functions and why those calls still require unsafe, including the suggested safe-wrapper approach.
- C Header Generation Workflow. Describe how to prepare a Rust API for cbindgen, generate its C header, and give the header and static library to a C build. Explain why manual generation is useful while experimenting and why a stable project can automate it in build.rs.
- Automated C header generation. Explain that cbindgen can generate a C header during the build process, and that adding it to Cargo.toml’s build-dependencies supports generating the header on each build.
- Application ownership during migration. Distinguish who controls an existing C product during migration from who might control a new Rust application that reuses C libraries.
- First module selection. Justify choosing pure logic as an early migration target and leaving hardware-adjacent code until later, if it moves at all.
- Small C-shaped interface. Describe the recommended shape of the Rust–C boundary and explain why it should remain small.
- Switchable module rollout. Trace how to integrate and roll out one Rust replacement while preserving a way back to the C version.
What it builds on
- The Cortex-M exception handling model (chapter 4) · The Cortex-M exception handling model.
- Writing Inline Assembly with asm!() (chapter 5) · Writing inline assembly in Rust.
- Struct layout (chapter 5) · Struct layout as a memory-placement concern.
- Understanding data alignment and layout (chapter 5) · The role of data alignment in memory layout.
- Optional build-time customization with build.rs (chapter 3) · The role of build.rs in build-time customization
- Targets and target triples explained (chapter 2) · The target information used when building for embedded hardware
- Implementing the panic handler (chapter 4) · The panic-handler requirement in a minimal no_std application.
- Initializing Rust’s runtime in a bare-metal environment (chapter 4) · the bare-metal reset handler and startup initialization
Section by section
Introduction
The chapter introduction explains why integrating embedded Rust with existing C code requires care at the language boundary.
- Rust-C boundary responsibility: Explain why an embedded Rust project may need to interact with C and why Rust’s safety guarantees do not automatically cover calls or memory shared across that boundary.
Why it matters: This is why using existing C components takes more than simply calling them from Rust.
Key terms: language boundary, memory safety, C, Rust
8.1 Understanding Rust FFI & ABI
Introduces bidirectional Rust–C FFI in embedded systems and explains why crossing the language boundary requires attention to ABI compatibility and safety.
- Bidirectional embedded FFI: Explain that FFI lets Rust call C and lets C call Rust, often to integrate existing embedded components such as legacy libraries, vendor HALs, startup code, or RTOS kernels.
Why it matters: The direction of the call determines which side provides an interface for the other to use. - Cross-language compatibility risks: Explain why matching and linking code is not enough for a reliable language boundary: calling conventions, data layout, and type representations must agree. Describe how Rust makes FFI explicit and unsafe by default so the developer must attend to the ABI, layouts, and signatures.
Why it matters: An FFI call can link successfully yet still fail in ways that are difficult to notice.
Key terms: Foreign Function Interface (FFI), vendor HAL, RTOS kernel, ABI, calling conventions, data layout, type representations, unsafe
8.1.1 Setting up the bridgeheads
This subsection introduces the declarations and symbol names that connect Rust and C, and explains the safety responsibilities at that boundary.
- External declarations and C ABI: Explain that `extern` declares a function or static variable outside Rust and specifies an ABI, usually `"C"`, so the declaration follows the target platform’s C calling convention and type layout.
Why it matters: Rust and C must agree on the interface used to call a function. - Trust in external declarations: Explain why an `unsafe extern` block is a promise about declarations the compiler cannot verify, and distinguish that from an individual item marked safe to call.
Why it matters: The declaration’s safety marker does not mean Rust has checked the external definition. - Stable names for C linkage: Explain why an exported Rust function uses `#[unsafe(no_mangle)]`: it keeps the written symbol name so a C linker can resolve it, while overriding Rust’s normal name mangling.
Why it matters: C needs a predictable symbol name to find a Rust-exported function. - Defined overflow in exported functions: Justify the example’s use of `wrapping_add()` rather than plain `+` in a Rust function exported to C.
Why it matters: An exported function should have defined behavior for ordinary inputs, including overflow.
Key terms: extern, ABI, "C", calling convention, unsafe extern block, safe, #[unsafe(no_mangle)], name mangling, symbol names, linkage
8.1.2 The ABI and the procedure call standard
Explains the binary contract that lets C, Rust, and hand-written assembly call one another, with Cortex-M calling and stack rules as examples.
- ABI interoperability contract: Explain that an ABI lets separately compiled code agree on calling conventions, data layout, and symbol names at the machine-code level.
Why it matters: The ABI explains why matching source-level function names and types is not enough for cross-language calls. - Cortex-M procedure call rules: Describe the PCS as the function-calling part of the ABI and trace where ordinary Cortex-M arguments and return values go, including 64-bit arguments, stack spillover, and the hard-float exception.
Why it matters: These rules give both sides of a function call the same place to look for each value. - Public boundary stack alignment: Explain the stack-alignment rule at a public interface and why violating it can cause delayed or unpredictable failure rather than an immediate crash.
Why it matters: Code that seems to run is not evidence that its cross-language stack alignment is correct. - Assembly handler PCS obligations: Distinguish what Cortex-M hardware does automatically on an exception from what a hand-written assembly handler must still do before calling C or Rust.
Why it matters: Automatic exception entry does not remove the calling-convention duties of hand-written handler code.
Key terms: Application Binary Interface, ABI, calling convention, data layout, symbol naming, PCS, Procedure Call Standard, R0, R1, R2
8.2 Calling C from Rust
This section introduces Rust’s FFI as the way to reuse existing C code in embedded Rust firmware.
- Existing C code integration: Explain why embedded Rust projects may need to use existing C code and what Rust’s FFI enables at a high level.
Why it matters: It gives you a way to use established C components without rewriting them before moving firmware to Rust.
Key terms: FFI, vendor’s HAL, protocol stack, device driver
8.2.1 Naming conventions and the ffi module
This subsection explains why C naming conventions produce Rust lint warnings and why C declarations and their lint suppressions should be confined to an FFI module.
- Module-scoped C naming lints: Explain why C identifiers can trigger Rust naming warnings and why the declarations and lint suppressions should be kept in one module rather than applied crate-wide.
Why it matters: The FFI boundary can accommodate C’s names without giving up naming checks in your own Rust code.
Key terms: ffi module, allow attributes, lint suppressions, C declarations
8.2.2 Scalar type compatibility
This section explains how to choose Rust scalar types that match C types on the actual embedded target, avoiding host-dependent FFI mistakes.
- Target-matched scalar bindings: Explain that Rust and C scalar types in an FFI binding must have compatible sizes and alignments on the target. Describe why i32 matches C int on ARM Cortex-M and why core::ffi types are a portable choice.
Why it matters: A Rust binding can compile yet pass the wrong representation across the C boundary. - Cross-target scalar pitfalls: Describe how C char signedness and long size can differ by platform, and explain why host-based assumptions or unverified usize and isize choices can make target bindings wrong.
Why it matters: A binding based on host assumptions can be silently wrong on the device.
Key terms: scalar types, core::ffi, c_int, c_uint, i32, char, AAPCS, long, usize, isize
8.2.3 Struct layout and alignment
This section explains why structs shared between C and Rust need a C-compatible memory layout and how to check that layout at compile time.
- C-compatible struct layout: Explain why a Rust struct shared with C needs #[repr(C)] and what that attribute guarantees.
Why it matters: A shared struct must mean the same thing at each memory address to both languages. - Alignment and padding example: Trace the padding and field offsets in the section’s six-byte C struct, and describe the consequence of passing a differently laid-out Rust struct to C.
Why it matters: The example shows how a layout mismatch can corrupt data without an obvious failure. - Compile-time layout checks: Describe how the section recommends validating a shared struct’s layout and why compilation-time checks are preferable to a runtime assertion.
Why it matters: A build-time failure catches a broken interface before firmware reaches the device.
Key terms: #[repr(C)], struct layout, alignment, padding, uint16_t, offset, const assertion, C11, runtime assert_eq!()
8.2.4 Enums, transparent wrappers, and layout lints
This section explains how to make enum-like values predictable and safe across a Rust–C boundary, using fixed-width types, transparent wrappers, validation, and layout lints.
- Predictable enum representation: Explain why a plain #[repr(C)] Rust enum is not guaranteed to have a fixed size, and describe how Rust and C can agree on a fixed-width representation.
Why it matters: An unnoticed size mismatch can make every field after an enum in a shared struct be read from the wrong place. - Transparent single-value wrappers: Describe how #[repr(transparent)] lets Rust distinguish a wrapped value from its underlying integer type without changing its memory representation for C.
Why it matters: It provides a Rust-side type distinction without changing the value C sees in memory. - Validation of C-supplied states: Explain why a fixed-width Rust enum is still unsafe for unchecked values supplied by C, and describe the integer-wrapper-and-check approach.
Why it matters: Checking C-supplied values prevents an invalid byte from becoming an invalid Rust enum value. - FFI layout lint enforcement: Distinguish the two Rust FFI layout lints by direction and explain why the section recommends treating their warnings as errors.
Why it matters: Build-stopping lint errors are harder to overlook than warnings in a long build log.
Key terms: #[repr(C)], #[repr(u8)], typedef, uint8_t, DeviceState, #[repr(transparent)], SensorId, u16, uint16_t, CheckedDeviceState
8.2.5 Encapsulating unsafe behind safe interfaces
This section explains how safe Rust wrappers can localize unsafe C calls, enforce input rules, and translate C failures into Rust results.
- Safe wrappers at FFI boundaries: Explain why foreign calls are unsafe by default and how a safe Rust wrapper confines the unsafe call while enforcing an input rule, such as passing only non-negative arguments to C's add().
Why it matters: Keeping C calls behind reviewed wrappers limits how much of the Rust application must account for C's safety rules. - C errors as Rust results: Describe how a wrapper can translate a raw C result into a Rust Result at the FFI boundary when the call can fail in more than one way.
Why it matters: Callers can handle success and failure through a clear Rust interface rather than interpreting raw C results themselves.
Key terms: unsafe, safe Rust function, FFI boundary, trust boundary, invariant, raw C result, Rust Result
8.2.6 Linking C code: direct and indirect
This section explains how to link C code into an embedded Rust build, either from a prebuilt library or by compiling C sources with a build script, and warns about keeping compiler settings compatible.
- Direct linking of prebuilt libraries: Explain when to use #[link] for a prebuilt C static library, how its library name is written, and why the linker may also need a search directory.
Why it matters: Naming a library is not enough if the linker cannot find its file. - Build script C compilation: Describe how build.rs and the cc crate compile C source and link it during a normal Cargo build, and explain why the Rust declaration no longer needs #[link].
Why it matters: A build script makes compiling and linking project-owned C code part of the ordinary Cargo build. - Matching C and Rust targets: Explain what target settings cc selects by default and when extra Rust-side hardware settings must be mirrored with .flag() for C compilation.
Why it matters: Matching these settings helps prevent C and Rust code from silently being built for different hardware assumptions.
Key terms: #[link], static library, libmy_c_lib.a, .cargo/config.toml, build.rs, cc crate, cc::Build::compile(), Cargo, target, -C target-cpu
8.3 Calling Rust from C
This introduction explains why a C project calling Rust needs a simple, predictable interface rather than assuming Rust’s safety guarantees carry across the boundary.
- C-facing Rust interface: Explain why calling Rust from an existing C project requires attention to the boundary between the languages. Describe the need for predictable symbol names, data types, and linking.
Why it matters: This explains why a Rust function cannot simply be treated as an ordinary C function without considering its interface.
Key terms: safety guarantees, rich type system, symbol naming, data types, linked together
8.3.1 Exporting functions and data
This section explains how to expose Rust functions and immutable static data to C, and why C declarations must preserve Rust’s immutability.
- C-callable Rust function exports: Explain why a Rust function called from C needs both `extern "C"` and `#[unsafe(no_mangle)]`, and distinguish their roles from `pub`.
Why it matters: C needs both a compatible call convention and a resolvable symbol name to call Rust code. - Immutable Rust globals in C: Explain why C should declare an exposed immutable Rust static as `const` and what can happen if it does not.
Why it matters: A matching `const` declaration turns a possible firmware runtime failure into a C compile-time error.
Key terms: extern "C", #[unsafe(no_mangle)], pub, calling convention, symbol, static, const, flash memory, cortex-m-rt
8.3.2 A minimal no_std static library
This section shows how to build a minimal no_std Rust static library for Cortex-M that a C program can link, and how to verify its exported symbol.
- Panic Handler in Static Libraries: Explain why this no_std static library includes a panic handler even though it has no main function.
Why it matters: It prevents the mistaken assumption that only standalone no_std programs need a panic handler. - C Linkable Static Archive: Describe how Cargo is configured to produce the Rust library in a form a C program can link.
Why it matters: The C build needs a linkable archive, not an ordinary Rust binary. - Unmangled Export Verification: Explain how the example checks that its function is exported under the name C will use.
Why it matters: Checking the archive’s symbol name helps catch an export-name problem before linking it from C.
Key terms: #[panic_handler], no_std, staticlib, crate-type = ["staticlib"], static archive, Cortex-M target, libmy_rust_lib.a, nm, square, #[unsafe(no_mangle)]
8.3.3 Consuming the library from C
This section shows how a C program declares and links a Rust static library, and what extra linking considerations apply to bare-metal firmware.
- C Declarations for Rust Functions: Describe how a C header makes Rust library functions callable from a C program, and explain why the header may include an extern "C" block.
Why it matters: The C caller needs declarations that match the library's callable interface. - Static Library Linker Selection: Explain how gcc is directed to find and select the Rust static library using -L and -l.
Why it matters: These flags tell the C build where to find the Rust archive and which archive to link. - Bare-Metal Firmware Link Requirements: Explain the roles of -T and -nostartfiles and why linking successfully without the specified bare-metal startup components does not yield flashable firmware.
Why it matters: A successful link alone does not establish that the output can start and run on the device. - Unused Static Library Code Removal: Explain why the section enables compile-time function and data sections and link-time garbage collection when linking a Rust staticlib into C firmware.
Why it matters: Discarding unreferenced archive contents helps keep the firmware limited to code it uses.
Key terms: C header, extern "C", -L, static library, libmy_rust_lib.a, -T, -nostartfiles, linker script, vector table, reset handler
8.3.4 Error propagation with integer codes
Explains how Rust functions called from C can report errors with integer codes while preserving pointer safety contracts and preventing panics from crossing the boundary.
- C-compatible error codes: Explain why a Rust function called from C returns integer error codes instead of exposing Result or Option, and describe the usual meanings of zero and negative values.
Why it matters: Integer codes give C callers an error-reporting convention they can recognize without understanding Rust types. - Output pointer safety contract: Explain why an output parameter from C is taken as a checked raw pointer rather than a Rust mutable reference, and why the exported function is still declared unsafe.
Why it matters: A null check prevents one mistake, but it does not make every pointer supplied by C safe to use. - Panic-free division errors: Explain why checking only for a zero divisor is insufficient and how checked_div addresses the division failures without using a panic to report an error to C.
Why it matters: Handling both division failures keeps a Rust panic from becoming the way an exported function reports an error.
Key terms: Result, Option, integer error codes, output parameter, raw pointer, *mut i32, &mut i32, pub unsafe extern "C" fn, division by zero, i32::MIN / -1
8.4 Advanced FFI topics
Introduces arrays passed as pointers, C strings, and callbacks as FFI cases that need more care than scalars and structs.
8.4.1 Arrays and C strings
This section explains how to pass arrays and C strings across the Rust–C boundary and how to keep pointers valid when C retains them.
- Array Pointers and Lengths: Describe how a Rust slice is passed to a C function that expects an array pointer and length.
Why it matters: The C function needs both the address of the array data and its length. - NUL-Terminated C Strings: Distinguish Rust strings from C strings and explain how &CStr and C string literals help when passing text to C.
Why it matters: Without a terminator, C may keep reading beyond the intended string. - Retained Pointer Lifetimes: Explain why a pointer passed for one C call must not be retained afterward and describe what to provide when C needs the data later.
Why it matters: A delayed C operation can otherwise use memory that Rust has already reused.
Key terms: slice, raw pointer, as_ptr(), length, &str, C string, NUL terminator, &CStr, C string literal, pointer
8.4.2 Callbacks from C into Rust
This section shows how a Rust function can be registered as a callback for a C library to invoke later, and explains the limitation of a bare C function pointer.
- Callback registration and timing: Explain how a callback differs from an ordinary function call: code supplies a function in advance, and the receiving library calls it later when an event occurs.
Why it matters: The distinction tells you who controls when the Rust function runs. - Rust to C callback flow: Trace the example from declaring the C functions in a Rust extern block through registering rust_callback() and triggering its invocation from C. Explain why the supplied callback is an extern "C" fn.
Why it matters: Following both sides of the call makes clear how C can invoke a function supplied by Rust. - Bare function pointer limitation: Explain why the example’s C-style callback cannot capture surrounding variables like a Rust closure.
Why it matters: It explains why passing a bare callback does not also pass the data a closure might capture.
Key terms: callback, register_callback(), trigger_callback(), extern block, extern "C" fn, C function pointer, rust_callback(), bare function pointer, Rust closures, capture variables
8.4.3 Callbacks with context
This section shows how a C callback can carry user-defined context into Rust, how a Rust trampoline uses it, and what safety and portability conditions the example relies on.
- Callback context pointer pattern: Explain how a C library accepts a generic context pointer alongside a callback, stores the two together, and returns the pointer unchanged on each callback.
Why it matters: The returned pointer lets a callback work with state chosen by its caller. - Rust callback trampoline flow: Trace the example from install() registering count_events() and a pointer to EVENT_COUNT through to the callback casting that returned pointer to an AtomicU32 pointer and incrementing the counter.
Why it matters: Following the pointer through registration and invocation makes the C-to-Rust handoff understandable. - Context pointer safety contract: Justify why converting the returned context pointer requires unsafe code and why count_events() is an unsafe extern "C" function.
Why it matters: The cast is sound only when the pointer’s validity and actual type match the assumptions made in Rust. - Persistent atomic event counter: Explain why EVENT_COUNT is static and atomic, and state the portability limit given for its fetch_add operation.
Why it matters: The example needs state that survives each callback and can be updated safely under its stated concurrency assumption.
Key terms: callback, ctx, user_data, void*, install(), register_callback_ctx(), count_events(), trampoline, EVENT_COUNT, AtomicU32
8.5 Automating the interface: bindgen and cbindgen
Explains why growing embedded Rust–C projects use generated bindings and identifies the direction of each generation tool.
- Automated Rust C interface maintenance: Explain why hand-maintained Rust–C bindings become difficult as projects grow, and distinguish what bindgen and cbindgen generate.
Why it matters: This distinction helps you choose the right tool when an interface changes.
Key terms: bindings, bindgen, cbindgen, C headers
8.5.1 bindgen: from C headers to Rust
This section shows how to generate focused Rust FFI declarations from C headers with bindgen while preserving compatibility with the C library’s ABI.
- Header-to-binding workflow: Describe how to collect the needed C headers, include them through one wrapper header, run bindgen, and bring the generated declarations into a Rust project behind safe wrapper functions.
Why it matters: This replaces hand-written declarations while keeping unsafe FFI use behind a safer project interface. - Focused no_std bindings: Explain how to keep generated bindings suitable for an embedded no_std project and limited to the symbols it needs, including the roles of allowlists and blocklists.
Why it matters: Vendor headers can pull in many irrelevant declarations, including names unsuitable for a no_std target. - Matching the C ABI: Justify passing the embedded target to libclang and matching any ABI-affecting compiler flags to the flags actually used to build the C library, especially for enum sizing.
Why it matters: Bindings generated with the wrong type sizes or layout can disagree silently with the compiled C library.
Key terms: bindgen, C headers, wrapper.h, Rust FFI declarations, safe wrapper functions, --use-core, core::ffi, allowlist, blocklist, no_std
8.5.2 Automating bindgen in build.rs
This section shows how to generate bindgen declarations during a Cargo build, include them in Rust code, and use them without exposing unsafe foreign calls throughout the crate.
- Automated binding output: Explain how build.rs automates bindgen for repeatable builds and why generated bindings belong in Cargo’s OUT_DIR rather than src/.
Why it matters: Keeping generated files in Cargo’s build output makes automated builds repeatable without triggering needless rebuilds. - Build script linking directives: Describe what the two cargo: linking directives tell Rust’s linker about the C static library.
Why it matters: Generated declarations alone do not tell the build where to find and link the C implementation. - Including generated declarations: Trace how Rust finds the bindings file in OUT_DIR and brings its declarations into a named module.
Why it matters: The bindings live in a build-managed folder, so the crate must include them explicitly to use their declarations. - Generated call safety boundary: Explain how the module wrapper affects calls to generated functions and why those calls still require unsafe, including the suggested safe-wrapper approach.
Why it matters: Generating and organizing bindings does not remove the unsafe boundary around calls into C.
Key terms: build.rs, bindgen, [build-dependencies], OUT_DIR, src/, cargo:, rustc-link-search, rustc-link-lib=static=example, libexample.a, env!("OUT_DIR")
8.5.3 cbindgen: from Rust to C headers
This section explains how cbindgen turns a Rust C-facing API into a header for C projects, using a checksum example to highlight an unsafe pointer contract and a generated type-mapping choice.
- C Header Generation Workflow: Describe how to prepare a Rust API for cbindgen, generate its C header, and give the header and static library to a C build. Explain why manual generation is useful while experimenting and why a stable project can automate it in build.rs.
Why it matters: The generated header lets a C project consume the Rust library through its C-facing interface. - Checksum Pointer Safety Contract: Explain why the example checksum function cannot claim to be safe merely because it checks its input pointer for null, and describe the contract the section recommends exposing.
Why it matters: A C-callable signature must not imply that a null check makes arbitrary pointer-and-length inputs valid. - Generated Usize Type Choice: Distinguish cbindgen’s generated uintptr_t for Rust usize from the size_t used in the earlier hand-written example, and explain when the choice can matter.
Why it matters: Checking the generated header can reveal a type choice that differs from a hand-written C declaration.
Key terms: cbindgen, cbindgen.toml, language = "C", #[unsafe(no_mangle)], extern "C", fixed repr, checksum, null check, len, unsafe extern "C" fn
8.5.4 Automating cbindgen in build.rs
This subsection explains how automating cbindgen in the build process keeps a C header in sync with a Rust static library.
- Automated C header generation: Explain that cbindgen can generate a C header during the build process, and that adding it to Cargo.toml’s build-dependencies supports generating the header on each build.
Why it matters: A header regenerated with each build is less likely to fall out of sync with the library a C project uses.
Key terms: cbindgen, build-dependencies, Cargo.toml, C header, Rust static library
8.6 Migration strategies
This section lays out an incremental way to add Rust to an existing C firmware project without committing to a wholesale rewrite.
- Application ownership during migration: Distinguish who controls an existing C product during migration from who might control a new Rust application that reuses C libraries.
Why it matters: Keeping the working application in charge lets a team introduce Rust without replacing its startup and build structure first. - First module selection: Justify choosing pure logic as an early migration target and leaving hardware-adjacent code until later, if it moves at all.
Why it matters: A self-contained first module makes the migration easier to test and less dependent on difficult hardware interfaces. - Small C-shaped interface: Describe the recommended shape of the Rust–C boundary and explain why it should remain small.
Why it matters: A narrow interface limits duplicate maintenance and confines the code that needs manual safety review. - Tests and layout checks: Explain what checks accompany a migrated module and what kind of interface breakage they catch.
Why it matters: These checks can expose a broken C–Rust agreement before the firmware reaches a device in the field. - Switchable module rollout: Trace how to integrate and roll out one Rust replacement while preserving a way back to the C version.
Why it matters: A switchable rollout lets the team validate Rust on real hardware without losing a quick fallback.
Key terms: static library, main(), C application, pure logic, cargo test, hardware-adjacent code, boundary, fixed layout, integer error codes, unsafe
8.7 Summary
Concepts explained in this chapter
- rust bindgenbindgen is a tool that generates Rust foreign-function interface declarations from C and C++ headers.
- static libraryAn archive of compiled object code that a linker incorporates into an executable during linking.
- c-style enumA C type whose values are named enumerators.
- exact-width integer typeA fixed-width integer type is an integer type whose bit width is specified rather than selected by implementation defaults.
- repr(transparent)repr(transparent) is a Rust representation attribute that gives a single-field wrapper the same memory representation as its field.
- repr(u8)repr(u8) is a Rust representation attribute that gives an enum an unsigned 8-bit integer representation.
- safe wrapperA safe wrapper is an interface that encapsulates operations requiring unsafe interaction behind safe-to-call abstractions.
- raw pointerRaw pointer dereferencing accesses memory through a Rust raw pointer without the safety guarantees of an ordinary reference.
- callbackA callback is a function supplied to another component so that component can invoke it later in response to a particular condition or event.
- foreign function interfaceA mechanism for declaring and calling functions across programming-language boundaries using compatible binary conventions.
- context pointerA generic pointer passed alongside a callback function pointer so a library can return associated caller-provided data when invoking the callback.
- no_mangleThe Rust no_mangle attribute preserves an item's externally visible symbol name instead of applying name mangling.
- application binary interfaceAn application binary interface specifies binary-level conventions for calling functions, representing data, and interoperating between compiled software components.
- bindingA declaration describing a foreign-language function or data type so code in another language can interact with it.
- C representation`repr(C)` is a Rust representation attribute that applies C-compatible layout rules to a type.
- memory layoutA memory layout specifies the placement of a program's code, data, stack, and other regions in memory.
- cbindgencbindgen is a tool that generates C and C++ header files from Rust source code.
- trampolineA small intermediary function that adapts a generic callback interface to the specific function and data types expected by the implementation.
- unsafe RustUnsafe Rust is Rust code that uses operations requiring the programmer to uphold safety invariants the compiler cannot verify.
- hardware registerA processor register is a small storage location directly accessible to the processor for holding values during execution.
- alignmentAlignment is the placement of a data object at an address satisfying the boundary requirements of its representation or hardware access.
- no_std programno_std is a Rust crate configuration that excludes the standard library.
- build scriptA Cargo build script is a Rust program, conventionally named build.rs, that Cargo runs before compiling a package to perform build-time tasks.
- panic handlerA panic handler is the Rust-defined function that determines how a panic is handled in a target without the hosted panic runtime.
- stringA string is a sequence of characters represented as data.
- unsafe blockAn unsafe block is a Rust construct in which operations requiring explicit programmer verification, such as raw-pointer dereferencing, are permitted.
These guides are generated from the text of Manning books by Manning's knowledge graph and link to the sections they draw on. The full books are available on liveBook and at manning.com.
