Sub topic 1
What FFI Is and Why the C ABI Matters
Prerequisites
This chapter assumes you have the following:
- Basic Rust: ownership, borrowing, structs, and
Result. - Comfort with Cargo projects:
cargo new,cargo run, andCargo.toml. - Basic C: pointers, structs, and
malloc/free. - A general idea of what
unsafemeans in Rust. You don't need to have written much of it.
The examples need Rust 1.82 or newer. That release made the unsafe extern block syntax stable. In older compilers, write extern "C" without the unsafe keyword.
What FFI means
A foreign function interface (FFI) is the mechanism a language uses to call code written in another language. "Foreign" means the code was compiled by a different toolchain, with different rules about types, memory, and error handling.
Rust programmers reach for FFI for a few common reasons:
- A mature C library already solves the problem, such as compression, cryptography, image decoding, or a database client. Rewriting it costs more than binding to it.
- The operating system exposes its services as C functions. Examples are POSIX calls on Linux and macOS and the Win32 API on Windows.
- You are adding Rust to an existing C codebase one component at a time.
- Another language, such as Python or Ruby, needs to call your Rust code. It usually does so through a C-shaped interface.
This tutorial covers the first direction: Rust calling C. The reverse direction uses the same ideas, so most of what you learn carries over.
API versus ABI
An API (application programming interface) is the contract at the source level. It covers function names, parameter types, and what each function means. A header file such as point.h is an API description.
An ABI (application binary interface) is the contract at the machine level. After compilation, no types or parameter names remain. There are only bytes, registers, stack slots, and symbol names. For two separately compiled pieces of code to work together, they must agree on all of these:
- Symbol names. The linker connects a call to a function by looking up a name. A C function
point_distancenormally appears in the object file as the symbolpoint_distance. A Rust function's symbol is mangled, which means the compiler encodes the module path and a hash into it. - Calling convention. This says where arguments go and where the return value comes back. On x86-64 Linux and macOS (the System V ABI), the first six integer or pointer arguments go in the registers
rdi,rsi,rdx,rcx,r8, andr9. Floating-point arguments go inxmm0throughxmm7. An integer return value comes back inrax. On 64-bit Windows, the registers differ:rcx,rdx,r8, andr9. - Type sizes and representation. How many bytes is an
int? How is adoubleencoded? How is aboolstored? - Struct layout. The order of fields, their sizes, and the padding between them must match.
- Who cleans up the stack, and which registers a function must preserve. The caller and callee have to agree on both.
If one side puts an argument in rdi and the other reads it from rsi, the program reads garbage. The compiler can't warn you, because by link time each side has been translated to machine code.
Why C became the common ground
ISO C does not define an ABI. Each platform does, and C compilers on that platform follow its document. Examples are the System V AMD64 psABI, the Arm AAPCS64, and the Microsoft x64 convention. When people say "the C ABI," they mean "whatever the platform's C compilers agree on."
That agreement is the reason C is the common language of FFI:
- Every major operating system's libraries and system calls are described in C terms.
- The C ABI is small and stable. It has no overloading, no generics, no exceptions, and no classes, so the symbol and calling rules stay simple.
- Almost every language can call into and be called from the C ABI. A C-shaped interface is therefore the one that works everywhere.
C++ is a counterexample. Its name mangling and exception model vary between compilers, so C++ libraries normally expose an extern "C" layer if they want to be callable from other languages.
Why Rust needs `extern "C"`
Rust does not promise a stable ABI for its own functions. The default is the "Rust ABI," and the compiler is free to change it between versions. The Rust ABI is allowed to do all of these:
- Pass arguments in different registers than C does, or pass them by reference behind the scenes.
- Reorder the fields of a struct to reduce padding.
- Mangle symbol names in ways that change from release to release.
This freedom lets the compiler generate better code. It also means Rust code and C code cannot assume they agree on anything. You have to opt in to the C rules explicitly, in three places:
- The function.
extern "C"on a function or function pointer type selects the platform's C calling convention. - The data.
#[repr(C)]on a struct or enum selects C's layout rules. A later chapter covers this. - The symbol name. For Rust functions that C will call, an attribute disables mangling (
#[unsafe(no_mangle)]in edition 2024). Calling C from Rust does not need this.
The string "C" in extern "C" names the ABI. Rust supports other strings for other conventions, such as "system" for Windows API functions. This tutorial uses "C" throughout.
The path of a single call
The diagram shows what happens when Rust code calls a C function. Only two steps involve your source code. The rest is compilation and linking.
Two things in this path are worth remembering:
- The extern declaration is the only description of the C function that the Rust compiler ever sees. It does not read the C header or the C source.
- The linker matches only a name. It does not check that the declared signature matches the real function.
A first call
The smallest useful FFI program calls functions from the C standard library. The Rust standard library already links against libc on common platforms, so you don't need to configure the linker.
use std::ffi::{c_char, c_int, CString};
unsafe extern "C" {
fn abs(input: c_int) -> c_int;
fn strlen(s: *const c_char) -> usize;
}
fn main() {
let n = unsafe { abs(-3) };
let s = CString::new("hello").unwrap();
let len = unsafe { strlen(s.as_ptr()) };
println!("{n} {len}");
}This prints 3 5. The program has three parts:
- The
unsafe extern "C"block declares two functions that exist elsewhere. It gives their names, parameter types, and return types. The compiler trusts this declaration completely. c_intandc_charare Rust type aliases for C'sintandcharon the current platform. Using them instead ofi32andi8keeps the declaration correct on platforms where C's sizes differ. The next chapters cover them.- Each call sits in an
unsafeblock. The compiler cannot verify that the declaration matches the real function, so the programmer takes responsibility for that.
CString builds a null-terminated byte string, which is what C expects. The chapter on strings covers it.
What the compiler does not check
When Rust calls Rust, the compiler checks types and borrows across the whole program. When Rust calls C, those checks stop at the declaration. The table below compares the two cases.
| Concern | Rust calling Rust | Rust calling C |
|---|---|---|
| Argument and return types | Checked against the real function | Checked only against your declaration |
| Number of arguments | Checked | Checked only against your declaration |
| Pointer validity | References are always valid | Raw pointers can be null, dangling, or misaligned |
| Lifetimes and aliasing | Enforced by the borrow checker | Not tracked across the boundary |
| Memory ownership | Expressed in types such as `Box` | Documented in the C library's manual, if at all |
| Panics and exceptions | Unwinding is well defined | Unwinding into C is undefined behavior or an abort |
The compiler does not warn you when a declaration is wrong. Suppose you declared abs as taking an i64 on a platform where C's int is 32 bits. The program would compile and link, because the symbol name still matches. At run time the call would pass a value in the wrong form. The result might be a wrong answer, a crash, or something that works until you change compilers.
Common errors
- Declaring the wrong signature. The most frequent mistake is a type mismatch, such as using
i32for a Clong, or leaving out a parameter. Compare every declaration with the C header, not with memory. - Assuming a Rust struct matches a C struct. Without
#[repr(C)], Rust may reorder fields. A pointer to such a struct passed to C will be read with the wrong layout. - Forgetting that the linker only matches names. A typo in a function name produces a link error. A correct name with a wrong signature produces nothing at all until the program misbehaves.
- Treating the
unsafeblock as a formality. The block marks the places where your reasoning replaces the compiler's. Each one should have a reason you can state, such as "the pointer comes from a liveCString." - Using the Rust ABI by accident. A function pointer or declaration without
extern "C"uses the Rust ABI. Passing it to C compiles but fails at run time.
How the rest of the tutorial builds on this
Each later chapter handles one place where the two sides must agree. It covers C types, strings, struct layout, linking, ownership, and errors. It then covers callbacks, panics, and generated bindings. The common idea is the same each time. You describe the C side to Rust exactly, confine the unsafe code to a small area, and expose a safe interface on top.
Exercise
A teammate declares a C function int add(int a, int b) in Rust as fn add(a: i64, b: i64) -> i64 inside an unsafe extern "C" block. The program compiles, links, and runs on their laptop, but they report odd results on another machine. Explain why the compiler accepted it and what they should change.
Show answer
The compiler only checks calls against the declaration, and the linker only matches the symbol name add, so neither can detect that the declaration disagrees with the C function. The declaration is wrong because C's int is usually 32 bits, not 64. The values may be passed or returned in a different width than the C code expects, which is undefined behavior and may behave differently across platforms. They should declare it with std::ffi::c_int, as fn add(a: c_int, b: c_int) -> c_int, and check the signature against the C header.
Exercise
Why can't Rust call a normal Rust function from C just by knowing its name? Name two things about the Rust ABI that cause this.
Show answer
Rust does not promise a stable ABI for its default calling convention. First, the symbol name is mangled, so C cannot look it up by the plain source name. Second, the calling convention is unspecified and may differ from C's, so C could put arguments in registers that the Rust function does not read. The compiler may also reorder struct fields. To make a function callable from C, mark it extern "C", disable name mangling, and use #[repr(C)] for the types it passes.
Exercise
What is the difference between an API and an ABI? Give one example of each from a C library.
Show answer
An API is the source-level contract: function names, parameter types, and behavior, for example the declaration double point_distance(const point *a, const point *b); in a header. An ABI is the binary-level contract: symbol names, which registers hold arguments, type sizes, and struct layout, for example "on x86-64 System V, the two pointer arguments arrive in rdi and rsi, and the double result is returned in xmm0."