Level 3 · Systems· Lesson 8 of 11 · 30 min
FFI — talking to C
Calling C from Rust and Rust from C, repr(C), strings and ownership across the boundary, bindgen and cbindgen.
The C ABI is the lingua franca
Almost every language can call C functions, so C’s calling convention is how Rust interoperates with everything: operating systems, existing libraries, Python extensions, mobile apps. The boundary is inherently unsafe — the compiler cannot see the other side — so the craft is in making the unsafe surface small and wrapping it in a safe API.
Calling C from Rust
The C standard library is already linked into every Rust program, so we can call it directly:
use std::ffi::{c_char, c_int, CStr, CString};
unsafe extern "C" {
fn strlen(s: *const c_char) -> usize;
fn abs(x: c_int) -> c_int;
fn getenv(name: *const c_char) -> *const c_char;
}
/// A safe wrapper: all the pointer handling stays in here.
fn env(name: &str) -> Option<String> {
let name = CString::new(name).ok()?; // fails if `name` contains an interior NUL
// SAFETY: `name` is a valid NUL-terminated string that outlives the call.
let ptr = unsafe { getenv(name.as_ptr()) };
if ptr.is_null() {
return None;
}
// SAFETY: getenv returned a non-null pointer to a NUL-terminated string.
// We copy it out immediately, before anything could modify the environment.
Some(unsafe { CStr::from_ptr(ptr) }.to_string_lossy().into_owned())
}
fn main() {
let text = CString::new("hello from Rust").unwrap();
// SAFETY: valid NUL-terminated string; abs has no preconditions besides x != INT_MIN.
let (len, a) = unsafe { (strlen(text.as_ptr()), abs(-42)) };
println!("{len} {a}");
println!("PATH is set: {}", env("PATH").is_some());
}
Since the 2024 edition extern blocks are written unsafe extern, acknowledging that the declarations themselves are a promise: if a signature is wrong, calls are undefined behaviour. Individual items may be marked safe fn when they truly have no preconditions.
Strings
| Rust | C | Notes |
|---|---|---|
&str / String |
— | UTF-8, length-prefixed, no terminating NUL, may contain NUL |
&CStr |
const char * (borrowed) |
NUL-terminated, arbitrary bytes |
CString |
char * (owned by Rust) |
Build with CString::new; pass with .as_ptr() |
OsStr / OsString |
platform strings | Paths, environment; not necessarily UTF-8 |
A classic bug: CString::new("x").unwrap().as_ptr() — the temporary CString is dropped at the end of the statement and the pointer dangles. Bind the CString to a variable that outlives the call.
Types
Use the aliases in std::ffi (c_int, c_long, c_char, c_void) rather than guessing: long is 32 bits on Windows and 64 on Linux. Option<&T>, Option<Box<T>> and Option<extern "C" fn()> are guaranteed to have the same layout as a nullable pointer, which makes them convenient in signatures.
Layout: repr(C)
use std::mem::{align_of, size_of};
#[repr(C)]
struct CPoint {
tag: u8,
x: f64,
flag: u8,
}
struct RustPoint {
tag: u8,
x: f64,
flag: u8,
}
#[repr(C)]
#[derive(Debug, Clone, Copy)]
enum Status {
Ok = 0,
NotFound = 1,
Denied = 2,
}
fn main() {
println!("repr(C): size {} align {}", size_of::<CPoint>(), align_of::<CPoint>());
println!("default: size {} align {}", size_of::<RustPoint>(), align_of::<RustPoint>());
println!("{:?} = {}", Status::Denied, Status::Denied as i32);
}
repr(C) lays fields out in declaration order with C’s padding (24 bytes here); the default representation is free to reorder (16 bytes). Never pass a default-repr struct across FFI. For C enums, remember that C code can hand you any integer; receiving an out-of-range discriminant in a Rust enum is instant UB, so accept an integer and convert it with a checked TryFrom.
Calling Rust from C
Build the crate as a C library (crate-type = ["cdylib"] or "staticlib") and export functions with an unmangled name and the C ABI:
use std::ffi::{c_char, CStr, CString};
use std::panic::catch_unwind;
use std::ptr;
/// An opaque handle: C sees only a pointer.
pub struct Counter {
words: usize,
}
#[unsafe(no_mangle)]
pub extern "C" fn counter_new() -> *mut Counter {
Box::into_raw(Box::new(Counter { words: 0 })) // give ownership to C
}
/// # Safety
/// `c` must come from `counter_new` and not have been freed; `text` must be NUL-terminated.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn counter_feed(c: *mut Counter, text: *const c_char) -> i32 {
if c.is_null() || text.is_null() {
return -1;
}
let result = catch_unwind(|| {
// SAFETY: checked non-null above; validity is the caller's contract.
let (c, text) = unsafe { (&mut *c, CStr::from_ptr(text)) };
match text.to_str() {
Ok(s) => { c.words += s.split_whitespace().count(); 0 }
Err(_) => -2, // not UTF-8
}
});
result.unwrap_or(-3) // never let a panic cross the boundary
}
/// # Safety
/// `c` must come from `counter_new` and not have been freed.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn counter_report(c: *const Counter) -> *mut c_char {
let Some(c) = (unsafe { c.as_ref() }) else { return ptr::null_mut() };
CString::new(format!("{} words", c.words)).unwrap().into_raw()
}
/// # Safety
/// `s` must come from `counter_report`, and must not be used afterwards.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn counter_string_free(s: *mut c_char) {
if !s.is_null() {
drop(unsafe { CString::from_raw(s) }); // Rust allocated it, Rust frees it
}
}
/// # Safety
/// `c` must come from `counter_new`, and must not be used afterwards.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn counter_free(c: *mut Counter) {
if !c.is_null() {
drop(unsafe { Box::from_raw(c) }); // take ownership back and drop
}
}
fn main() {
// Exercising the C API from Rust, exactly as a C caller would.
unsafe {
let c = counter_new();
let text = CString::new("the quick brown fox").unwrap();
assert_eq!(counter_feed(c, text.as_ptr()), 0);
let report = counter_report(c);
println!("{}", CStr::from_ptr(report).to_str().unwrap());
counter_string_free(report);
counter_free(c);
}
}
The patterns to remember:
- Opaque handles:
Box::into_rawto hand out,Box::from_rawto take back. C never sees the layout. - Every allocation has a matching free function exported by the side that allocated.
- Errors are return codes, with out-parameters for results. No
Result, no panics. catch_unwindat the boundary. A panic escaping anextern "C"function aborts the process.- Check every pointer for null, and document every other precondition under
# Safety. #[unsafe(no_mangle)]is itselfunsafein the 2024 edition: a clashing symbol name is undefined behaviour at link time.
Tooling
| Tool | Direction | What it does |
|---|---|---|
bindgen |
C → Rust | Generates extern declarations and repr(C) types from C headers |
cc |
C → Rust | Compiles bundled C/C++ sources from build.rs |
pkg-config, vcpkg |
C → Rust | Locates system libraries from build.rs |
cbindgen |
Rust → C | Generates a C header from your extern "C" API |
cxx |
C++ ↔ Rust | A safe bridge with shared types and checked signatures |
PyO3, napi-rs, uniffi |
Rust → Python / Node / Swift, Kotlin | High-level bindings, no hand-written C layer |
Convention: a foo-sys crate contains the raw, unsafe bindings and the build script; a foo crate wraps it in a safe, idiomatic API. Callbacks into Rust are passed as extern "C" fn pointers plus a *mut c_void user-data pointer carrying your closure’s state.
Exercises
- Wrap
qsortfrom libc in a safefn sort_i32(xs: &mut [i32])by passing anextern "C" fncomparator. - Write a C header by hand for the
CounterAPI above, then check it againstcbindgen’s output. - Build the counter as a
cdyliband call it from Python withctypes. - Why is
counter_freebeing called twice undefined behaviour, and how could a safer handle design (for example integer handles into a table) detect it?
Check your understanding
Pick an answer to see the explanation.
1.Why must a struct shared with C be marked
#[repr(C)]?2.Rust allocates a string and hands the pointer to C. Who must free it?
3.What happens if a Rust panic unwinds out of an
extern "C"function into C code?