liveBook · Manning

Chapter 8: Rust-C Integration and Migration

What you will learn in chapter 8 of Embedded Software with Rust

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

What it builds on

Section by section

Introduction

The chapter introduction explains why integrating embedded Rust with existing C code requires care at the language boundary.

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.

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.

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.

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.

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.

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.

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.

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.

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.

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.

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.

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.

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.

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.

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.

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.

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.

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.

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.

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.

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.

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.

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.

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.

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

← Chapter 7: Managing stack and heap in resource-constrained systems

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.