liveBook · Manning

Foreign function interface

As explained in Embedded Software with Rust

A mechanism for declaring and calling functions across programming-language boundaries using compatible binary conventions.

A foreign function interface (FFI) lets Rust and C call one another across a binary boundary. Embedded firmware uses it to reuse C libraries, vendor HALs, drivers, startup code, or RTOS kernels. Calls depend on matching ABIs, signatures, and data layouts; mismatches can cause buffer overruns, stack corruption, or misaligned data. Rust makes the boundary explicit and unsafe because the compiler cannot verify external declarations. section 8.1 section 8.2

Use these patterns to make the boundary explicit and limit its risks:

  • Declare external functions in an unsafe extern block and name the ABI, commonly "C". The ABI selects target calling conventions, such as AAPCS on ARM Cortex-M. section 8.1.1
  • Match scalar types to the target C types. core::ffi provides corresponding C types; check target sizes, especially for long, and avoid usize or isize unless their sizes align. section 8.2.2
  • Keep unsafe calls inside small safe wrappers that validate inputs or translate failures into Result, so callers use a clean Rust interface. section 8.2.5
  • To expose Rust functions to C, use the C ABI and an unmangled symbol name. Make behavior explicit; for example, wrapping_add avoids panicking on overflow. section 8.1.1
  • Treat pointer-based arrays, C strings, and callbacks as cases needing additional care beyond plain scalars. section 8.4
unsafe extern "C" {
    fn c_function(arg: u32) -> u32;
}

fn main() {
    let my_number: u32 = 1986;
    // Wrap the call in an unsafe block to signify
    // that you are responsible for upholding safety.
    let result = unsafe {
        c_function(my_number)
    };
    println!("The result from the C function is: {}", result);
}

A minimal Rust declaration and call show where the C ABI is specified and where the call requires an unsafe block. section 8.1.1

How Embedded Software with Rust covers it

How deep it goes
Explains extern declarations, ABI and scalar matching, and safe wrappers; names arrays, C strings, and callbacks without detailing them.
Examples
Demonstrates a C function call, C-to-Rust scalar mappings, a Rust export, and checked wrappers for addition and hardware writes.
What you can do after
Apply Rust FFI to declare C functions, match target-compatible scalar types, export Rust symbols, and isolate unsafe calls behind checked wrappers.
How it connects
Links FFI to the C ABI, unsafe Rust, C scalar types, and Rust Result.

Also explained in

Compare how 4 books explain foreign function interface →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Embedded Software with Rust. The section links point to the parts of the book it draws on.