Sub topic 1
What FFI is and why the C ABI matters
Prerequisites
This chapter assumes you know basic Rust: ownership, borrowing, structs, and Result. You should be able to create and build a Cargo project. You should also know what a C pointer is, and what unsafe means in Rust. You don't need to have written any FFI code yet.
What FFI means
A foreign function interface (FFI) is a mechanism that lets code written in one language call code written in another. In this tutorial the "foreign" language is C, and the caller is Rust.
C is the usual target because so much existing software is written in it. Operating system APIs, compression libraries, database clients, and graphics drivers often expose a C interface. Rewriting them in Rust is rarely practical. FFI lets you reuse them.
What an ABI is
An API describes how source code talks to a library: function names, argument types, and return types. An application binary interface (ABI) describes how compiled code talks to other compiled code. It answers questions the source code never mentions:
- Which CPU registers or stack slots hold each argument?
- Which register holds the return value?
- How are structs laid out in memory, and how much padding sits between fields?
- What are the sizes of basic types such as
intandlong? - Who cleans up the stack after a call?
- How are symbol names written in the compiled file?
Both sides of a call must agree on every one of these answers. If they don't, the program reads garbage or crashes, and the compiler can't warn you, because it only sees one side.
Why Rust needs `extern "C"`
Rust does not promise a stable ABI. The compiler may reorder struct fields, change how arguments are passed, and mangle function names differently between versions. That freedom allows optimizations, but it means compiled Rust code can't be relied on to match what a C compiler produces.
C has no such flexibility in practice. Each platform defines a C ABI, and nearly every language and operating system can follow it. It works as a shared meeting point.
The string "C" in extern "C" selects that ABI. You use it in two directions:
unsafe extern "C" { ... }declares functions that C provides, so Rust can call them.extern "C" fn name() { ... }defines a Rust function that follows the C calling convention, so C can call it.
The rest of this tutorial builds on the first form, and returns to the second when we cover callbacks.
A first example
This program calls two functions from the C standard library. Rust programs already link against it on common platforms, so you need no extra setup.
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}");
}Running it prints 3 5.
Three details matter here:
- The
unsafe extern "C"block lists signatures only. There are no bodies, because the code lives in C. - The types are
c_intand*const c_char, noti32and&str. They match what C expects on the current platform. - Each call sits inside
unsafe. Rust can't read C source or machine code, so it can't check that your declaration matches the real function.
Why calls are unsafe
Safe Rust guarantees memory safety because the compiler checks every reference. Across the C boundary those checks stop. A C function can:
- Dereference a null or dangling pointer.
- Write past the end of a buffer.
- Keep a pointer after you free the memory.
- Read bytes in a way that violates Rust's type rules.
So the unsafe keyword marks a promise you make: "I have checked that this declaration is correct and that I'm passing valid arguments." Later chapters show how to keep that promise in one small place and expose a safe API to the rest of your program.
Common errors at this stage
- Using Rust types in declarations. Writing
i32for a Cinthappens to work on most platforms, butc_intstates your intent and stays correct where sizes differ. - Passing a Rust
&strto C. A&strisn't null-terminated and isn't a pointer tochar. The next chapters coverCStringandCStr. - Misdeclaring a signature. A wrong declaration compiles cleanly and fails later. Copy signatures from the library's header file.
- Forgetting to link. The C standard library is linked by default, but other libraries need explicit linking. A later chapter covers this.
Exercise
Why does Rust require extern "C" to call a C function, instead of using a normal Rust function declaration?
Show answer
Rust has no stable ABI, so the compiler is free to choose its own calling convention, struct layout, and name mangling. C code follows the platform's C ABI. extern "C" tells Rust to use that ABI for the call, so both sides agree on where arguments and return values live. Without it, the call would mismatch and cause undefined behavior.
Exercise
In the example above, why must the calls to abs and strlen be inside unsafe blocks, even though abs(-3) looks harmless?
Show answer
The compiler can't verify that the declaration matches the real C function, or that the arguments are valid. The unsafe block records that the programmer has taken responsibility for both. It applies to every foreign function, regardless of how simple the function seems.