Sub topic 1
What FFI Is and Why the C ABI Matters
Prerequisites
This chapter assumes basic Rust ownership, borrowing, structs, and Result. You should also know that C uses pointers and null-terminated strings, and that unsafe Rust requires you to uphold rules the compiler cannot verify.
What FFI and the C ABI Mean
Foreign function interface (FFI) is a way for code written in one language to call code written in another. Rust commonly uses FFI to call C libraries.
The application binary interface (ABI) defines how functions exchange data at the machine level. It includes calling conventions, type layouts, symbol names, and return values. Rust's default ABI is not a stable contract for C. The "C" ABI tells Rust to use the convention expected by C.
A call across this boundary is unsafe because an incorrect declaration can cause undefined behavior. Rust cannot check whether the C function exists, whether a pointer is valid, or whether the declared types match the compiled library.
Declaring and Calling C Functions
Declare foreign functions in an unsafe extern "C" block. Calling them requires an unsafe block. Keep each unsafe operation small and check its assumptions around the call.
use std::ffi::{c_char, c_int, CStr, CString};
unsafe extern "C" {
fn abs(input: c_int) -> c_int;
fn strlen(s: *const c_char) -> usize;
}
fn c_length(text: &CStr) -> usize {
unsafe { strlen(text.as_ptr()) }
}
fn main() {
let number = unsafe { abs(-3) };
let text = CString::new("hello").unwrap();
println!("{number} {}", c_length(text.as_c_str()));
}The declaration must exactly match the C header. c_int and c_char express C-compatible types instead of assuming that Rust's i32 or u8 always matches the target platform.
Matching Types and Strings
Use types from std::ffi for C primitives and pointers. A C string ends at the first zero byte, called a null terminator.
CStringowns a null-terminated string suitable for passing to C.CStrborrows a null-terminated string supplied by C or another owner.CString::newrejects interior null bytes, which prevents an early string ending.
Exercise
Why does a C function declaration use extern "C"?
Show answer
It selects the C ABI so Rust uses the calling convention and symbol interface that the C function expects.