FFI
FFI is how Rust calls C, and how C calls Rust. You declare extern "C" functions, match layouts with repr(C), and treat every crossing as unsafe.
Detailed Explanation
Rust cannot call a C library by guessing. You write an extern "C" { fn compress(buf: *mut u8, len: usize) -> i32; } block (or generate it with bindgen) that names the symbol, the argument types, and the calling convention. The call is unsafe because the compiler cannot check that the pointer is valid, that len is the buffer's length, or that the library is even linked.
Coming the other way, #[no_mangle] pub extern "C" fn add(a: i32, b: i32) -> i32 exports a symbol C can call. no_mangle keeps the name add instead of a Rust-mangled name. extern "C" uses the C ABI. Without both, a C compiler will not find the function, or will find it and pass arguments wrong.
Layout is a separate problem. A Rust struct { a: u8, b: u32 } may be reordered or padded differently from the C struct you think you are matching. #[repr(C)] adopts C's field order and alignment rules. #[repr(transparent)] is for newtypes that must have the same layout as their one field. Enums need an explicit repr if C will see them as integers. Strings are not C strings: you pass CString or a pointer plus length, never a Rust String by value.
Ownership across the boundary is a contract you write in comments. If C allocates, C frees, or you document a free_* function. If Rust allocates and passes a pointer out, Rust must not drop the value until C is done, which usually means std::mem::forget or ManuallyDrop plus an export that drops later. Passing a Rust &T to C is only valid for the duration of the call unless C does not store it.
When you reach for FFI: a C library with no Rust rewrite, an OS API, a plugin ABI. When you do not: a crate on crates.io that already wraps the library. Prefer bindgen plus a small safe wrapper over a hand-written extern block you will get wrong.
Code Examples
use std::ffi::CString;
use std::os::raw::c_char;
#[repr(C)]
struct Point {
x: i32,
y: i32,
}
extern "C" {
// Linked from libc; safe wrapper below.
fn strlen(s: *const c_char) -> usize;
}
fn c_len(text: &str) -> usize {
let c = CString::new(text).expect("no interior nul");
unsafe { strlen(c.as_ptr()) }
}
fn main() {
println!("{}", c_len("ada")); // prints: 3
let p = Point { x: 1, y: 2 };
println!("{} {}", p.x, p.y); // prints: 1 2
}Common Gotchas
Missing `repr(C)` silently mismatches fields
The program links and then reads the wrong bytes. This is UB, not a Rust panic.
Who frees is part of the API
Two frees is UB. No free is a leak. Document it next to the `extern` and wrap it in `Drop` on the Rust side.
`bindgen` is the default for large headers
Hand-written bindings drift. Generate them in `build.rs` or commit the generated file and review diffs.