Unsafe Rust and FFI
local graph
Chapter 23 — Unsafe Rust and FFI
Section titled “Chapter 23 — Unsafe Rust and FFI”Hic sunt dracones. (Here be dragons.)
Rust’s safety guarantees come with a cost: the compiler rejects programs it cannot verify. The borrow checker refuses code that is actually safe but falls outside the patterns it can analyze. Hardware interfaces require operations with no safe representation. Interoperability with C libraries demands crossing the boundary into a world where Rust’s guarantees do not hold. These situations require unsafe Rust, a mode where the programmer assumes responsibility for upholding invariants the compiler cannot check.
The existence of unsafe does not undermine Rust’s safety story. Rather, it makes that story complete. A language that forbade all unverifiable operations would be unable to implement its own standard library, interface with operating systems, or interoperate with existing code. Unsafe provides an escape hatch, but a disciplined one. The keyword marks exactly where unchecked assumptions live. Auditing code for potential memory safety issues becomes a matter of examining unsafe blocks, not reviewing every line. The vast majority of Rust code remains safe, with unsafe concentrated in well-tested foundations.
OOP developers familiar with Java’s native interface (JNI), C#‘s P/Invoke, or Python’s ctypes will recognize the problem space. Calling foreign code requires crossing a safety boundary. Rust’s approach differs in explicitness: the unsafe keyword documents exactly where guarantees are suspended, and the type system continues to help even when full safety is unavailable.
When unsafe is necessary
The Rust compiler tracks ownership, borrows, and lifetimes to guarantee memory safety without garbage collection. This tracking relies on specific patterns the compiler can analyze. Some operations are inherently outside this analysis: dereferencing raw pointers, calling external functions, accessing mutable statics, implementing certain traits. These operations require unsafe because the compiler cannot verify they preserve memory safety.
Raw pointer dereferencing is the most fundamental unsafe operation. Raw pointers (*const T and *mut T) are like references without the borrow checker’s oversight. Creating a raw pointer is safe, dereferencing it is not. The distinction matters: code can pass raw pointers around freely, but only unsafe blocks can access the data they point to. This design allows building abstractions where pointer manipulation happens safely but actual access is concentrated in verified locations.
Foreign function calls cannot be verified because the compiler knows nothing about external code. A C function might write beyond buffer bounds, return uninitialized memory, or create aliasing violations. When Rust code calls into C, it assumes responsibility for satisfying the foreign function’s requirements. Similarly, when C code calls into Rust, the Rust code must ensure it provides what C expects.
Mutable static variables create potential for data races. Multiple threads could access a mutable static simultaneously without synchronization. Rather than forbid mutable statics entirely (which would prevent certain low-level patterns), Rust requires unsafe to access them, placing the synchronization burden on the programmer.
Certain traits, marked with unsafe trait, require implementors to uphold invariants the compiler cannot verify. Send and Sync are the primary examples: a type is Send if moving it to another thread is safe, Sync if sharing references across threads is safe. Most types automatically derive these traits. Types that need manual implementation (perhaps wrapping raw pointers with known thread-safety properties) must use unsafe impl, asserting that the implementation upholds the trait’s contract.
Unsafe blocks and functions
The unsafe keyword applies to both blocks and functions, with different meanings. An unsafe block enables unsafe operations within a limited scope. An unsafe function declares that calling it requires upholding preconditions the compiler cannot check.
An unsafe block grants access to unsafe operations but does not change the safety of the surrounding code. The block’s contents run with additional permissions; everything outside remains subject to normal checking. This granularity encourages keeping unsafe code minimal. A function that needs one unsafe operation wraps that operation in a block rather than marking the entire function unsafe:
fn get_value(ptr: *const i32) -> Option<i32> { if ptr.is_null() { return None; } // Only the dereference is unsafe let value = unsafe { *ptr }; Some(value)}The function itself is safe to call. The null check ensures the pointer is valid before dereferencing. The unsafe block documents exactly where the unchecked operation occurs. Callers of get_value need not use unsafe; the function encapsulates the unsafe operation behind a safe interface.
An unsafe function, by contrast, shifts responsibility to callers. The function’s implementation might be entirely safe Rust, but its correct behavior depends on preconditions callers must satisfy. The classic example is from_utf8_unchecked, which creates a string from bytes without validating UTF-8:
// Standard library functionpub unsafe fn from_utf8_unchecked(bytes: Vec<u8>) -> String { // Implementation trusts that bytes are valid UTF-8 String::from_utf8_unchecked(bytes)}Calling this function requires an unsafe block. The caller asserts that the bytes are valid UTF-8. If they are not, the resulting string violates Rust’s invariants, potentially causing undefined behavior when the string is used. The unsafe marker on both the function declaration and the call site documents this shared responsibility.
The distinction guides API design. Prefer safe functions with internal unsafe blocks when safety can be encapsulated. Use unsafe functions when safety depends on caller-provided invariants that cannot be checked. A hash map’s internal array access might use unsafe indexing, but the public API is safe because bounds checking happens before access. A function that takes a raw pointer and dereferences it must be unsafe because safety depends on the pointer’s validity, which the function cannot verify.
Raw pointers and their guarantees
Raw pointers provide direct memory access without borrow checker involvement. They come in two flavors: *const T for read-only access and *mut T for mutable access. Unlike references, raw pointers can be null, can point to invalid memory, can alias freely, and have no lifetime tracking.
Creating raw pointers from references is safe because the pointer itself is inert until dereferenced:
let x = 42;let ptr: *const i32 = &x; // Safe: creating pointerlet mut y = 100;let mut_ptr: *mut i32 = &mut y; // Safe: creating mutable pointerDereferencing requires unsafe because the compiler cannot verify the pointer is valid:
let value = unsafe { *ptr }; // Unsafe: dereferencingunsafe { *mut_ptr = 200; } // Unsafe: writing through pointerRaw pointers support arithmetic. The offset and add methods compute new pointer positions. This enables iteration over contiguous memory, a pattern essential for implementing data structures:
fn sum_array(ptr: *const i32, len: usize) -> i32 { let mut total = 0; for i in 0..len { unsafe { total += *ptr.add(i); } } total}The safety requirements for pointer arithmetic mirror C: the resulting pointer must point within the same allocation or one past its end. Violating this causes undefined behavior even if the pointer is never dereferenced. This rule enables compiler optimizations but requires careful programming.
The NonNull<T> type provides a non-nullable raw pointer, useful for data structures where null should be impossible. It is a wrapper around *mut T that carries an invariant (non-null) in the type system. The type is particularly useful in unsafe code implementing collections, where null would indicate a bug rather than a valid state.
Converting between raw pointers and references uses explicit casts. The as keyword converts references to pointers. Reconstituting references from pointers requires unsafe and typically uses the &*ptr pattern or as_ref() method:
let reference: &i32 = unsafe { &*ptr };let option_ref: Option<&i32> = unsafe { ptr.as_ref() };When converting a raw pointer back to a reference, the programmer asserts that the pointer is valid, properly aligned, and that the resulting reference obeys aliasing rules. Getting this wrong causes undefined behavior.
FFI basics: calling C from Rust
Foreign Function Interface (FFI) enables Rust to call functions written in other languages and to be called from other languages. The primary target is C, the lingua franca of systems programming. Most operating systems, hardware drivers, and foundational libraries expose C interfaces. Rust’s FFI makes these accessible.
External functions are declared in extern blocks with the appropriate ABI (Application Binary Interface). The C ABI is most common:
extern "C" { fn strlen(s: *const std::ffi::c_char) -> usize; fn printf(format: *const std::ffi::c_char, ...) -> std::ffi::c_int;}Calling these functions requires unsafe because Rust cannot verify correctness. The declarations promise that functions with these signatures exist and use C calling conventions. Actually linking the functions happens at build time through system libraries or explicit linking configuration.
C and Rust have different type systems. The std::ffi module provides types for cross-language compatibility. CStr and CString handle null-terminated strings. Primitive types like c_int, c_char, and c_void match C’s types on each platform. Using these types rather than assuming i32 equals int ensures portability:
use std::ffi::{CStr, CString, c_char, c_int};
extern "C" { fn puts(s: *const c_char) -> c_int;}
fn print_message(msg: &str) -> Result<(), std::ffi::NulError> { let c_string = CString::new(msg)?; unsafe { puts(c_string.as_ptr()); } Ok(())}The CString::new function creates a null-terminated string, failing if the input contains internal null bytes (which C interprets as string termination). The as_ptr() method obtains a raw pointer suitable for C functions. The CString must outlive the function call; if it were dropped before puts returned, the pointer would dangle.
Linking to C libraries uses Cargo’s build script mechanism. A build.rs file instructs the linker:
fn main() { println!("cargo:rustc-link-lib=mylib"); println!("cargo:rustc-link-search=/usr/local/lib");}For complex C libraries, the bindgen tool generates Rust declarations from C headers automatically. This avoids manual transcription errors and keeps bindings synchronized with library updates. Running bindgen on a header file produces a Rust module with all type definitions and function declarations.
The following diagram illustrates the FFI boundary between Rust and C:
graph TD
subgraph RS["Rust Side"]
A["Safe Rust Code"] --> B["unsafe block"] --> C["extern C<br/>declarations"]
end
subgraph CS["C Side"]
D["C Library"]
end
C -- "FFI boundary" --> D
[!visual-conversion] The FFI boundary requires unsafe to cross. Print diagram (PDF 585, printed p. 575) recreated in Mermaid; labels verbatim.
Exposing Rust to other languages
Rust can also be called from other languages. A Rust library compiled with crate-type = [“cdylib”] produces a shared library with C-compatible exports. Functions marked with #[no_mangle] and extern “C” are accessible from C and any language with C FFI support.
The following diagram illustrates how Rust code is exposed to C callers:
graph TD
subgraph CA["C Application"]
M["main"] --> FC["function call"]
end
subgraph RL["Rust Library cdylib"]
NM["no_mangle extern<br/>C fn"] --> SR["Safe Rust<br/>Implementation"]
end
FC -- "FFI boundary" --> NM
[!visual-conversion] Rust library exposed to C callers. Print diagram (PDF 586, printed p. 576) recreated in Mermaid; labels verbatim. (The OCR had looped on this figure ~200 times and lost the page’s caption and the first two lines of the listing below, restored from the scan.)
#[no_mangle]pub extern "C" fn process_data( data: *const u8, len: usize,) -> i32 { if data.is_null() { return -1; }
let slice = unsafe { std::slice::from_raw_parts(data, len) };
// Safe Rust processing match process_slice(slice) { Ok(result) => result as i32, Err(_) => -1, }}
fn process_slice(data: &[u8]) -> Result<usize, ProcessError> { // Implementation using safe Rust Ok(data.len())}The #[no_mangle] attribute prevents Rust from renaming the function (name mangling normally encodes type information). The extern “C” specifier uses C calling conventions. The function receives raw pointers and primitive types, converts them to safe Rust types, and delegates to safe implementations.
Error handling across FFI boundaries requires translation. Rust’s Result type has no C equivalent. Common patterns include returning error codes (negative numbers often indicate failure), using out-parameters for results, or providing separate functions to retrieve error details. A header file documents the interface for C consumers:
#ifndef MYLIB_H#define MYLIB_H
#include <stdint.h>
int32_t process_data(const uint8_t* data, size_t len);
#endifLibraries like cbindgen generate C headers from Rust code automatically, ensuring header and implementation stay synchronized. This tooling reduces the maintenance burden of cross-language interfaces.
Considerations for mixed codebases
Section titled “Considerations for mixed codebases”Large projects often mix Rust with existing C or C++ code. The transition might be incremental, rewriting performance-critical or security-sensitive components while retaining existing code. Managing this boundary requires attention to memory ownership, error handling, and build integration.
Memory ownership across FFI is the most common source of bugs. When Rust allocates memory and passes it to C, questions arise: who frees the memory, and when? The same questions apply in reverse. Clear conventions prevent leaks and use-after-free:
/// Allocates a buffer that the caller must free with `free_buffer`.#[no_mangle]pub extern "C" fn allocate_buffer(size: usize) -> *mut u8 { let mut vec = Vec::with_capacity(size); vec.resize(size, 0); let ptr = vec.as_mut_ptr(); std::mem::forget(vec); // Prevent Rust from freeing ptr}
/// Frees a buffer allocated by `allocate_buffer`.#[no_mangle]pub extern "C" fn free_buffer(ptr: *mut u8, size: usize) { if ptr.is_null() { return; } unsafe { let _ = Vec::from_raw_parts(ptr, size, size); // Vec drops here, freeing memory }}The pattern of forget on allocation and from_raw_parts on deallocation transfers ownership across the FFI boundary. Documentation must make the ownership transfer explicit; C has no mechanism to enforce it.
Callback functions allow C code to invoke Rust closures. The challenge is that C function pointers cannot capture environment. Rust closures that capture variables must be converted to Box<dyn Fn> or similar, with the boxed closure passed as a separate context pointer:
type Callback = extern "C" fn(*mut std::ffi::c_void, i32);
extern "C" { fn register_callback(cb: Callback, context: *mut std::ffi::c_void);}
extern "C" fn trampoline(context: *mut std::ffi::c_void, value: i32) { let closure: &mut Box<dyn FnMut(i32)> = unsafe { &mut *(context as *mut Box<dyn FnMut(i32)>) }; closure(value);}
fn set_callback<F: FnMut(i32) + 'static>(f: F) { let boxed: Box<Box<dyn FnMut(i32)>> = Box::new(Box::new(f)); let context = Box::into_raw(boxed) as *mut std::ffi::c_void; unsafe { register_callback(trampoline, context); }}The double boxing handles the fat pointer issue: Box<dyn FnMut> is two pointers (data and vtable), while C expects a single pointer for context. The outer Box provides a thin pointer to the fat pointer.
Build integration for mixed codebases often uses the cc crate to compile C code alongside Rust:
fn main() { cc::Build::new() .file("src/legacy.c") .include("include") .compile("legacy");}This compiles C sources and links them into the Rust library. For C++ code, cc::Build::new().cpp(true) enables C++ compilation. The build script can also run pkg-config to find system libraries, generate bindings with bindgen, and handle platform-specific compilation flags.
Complete example: safe wrapper around C library
A practical pattern wraps a C library in a safe Rust interface. The wrapper handles memory management, converts between types, and presents an idiomatic Rust API. Consider wrapping a hypothetical C compression library:
// C declarationsmod ffi { use std::ffi::{c_int, c_void};
pub const COMPRESS_OK: c_int = 0; pub const COMPRESS_ERROR: c_int = -1; #[repr(C)] pub struct CompressContext { _private: [u8; 0], // Opaque type }
extern "C" { pub fn compress_init() -> *mut CompressContext; pub fn compress_free(ctx: *mut CompressContext); pub fn compress_data( ctx: *mut CompressContext, input: *const u8, input_len: usize, output: *mut u8, output_len: *mut usize, ) -> c_int; }}
// Safe wrapperpub struct Compressor { ctx: *mut ffi::CompressContext,}
impl Compressor { pub fn new() -> Option<Self> { let ctx = unsafe { ffi::compress_init() }; if ctx.is_null() { None } else { Some(Compressor { ctx }) } }
pub fn compress(&mut self, input: &[u8]) -> Result<Vec<u8>, CompressionError> { // Allocate output buffer (worst case: no compression) let mut output = vec![0u8; input.len() + 64]; let mut output_len = output.len();
let result = unsafe { ffi::compress_data( self.ctx, input.as_ptr(), input.len(), output.as_mut_ptr(), &mut output_len, ) };
if result == ffi::COMPRESS_OK { output.truncate(output_len); Ok(output) } else { Err(CompressionError::Failed) } }}
impl Drop for Compressor { fn drop(&mut self) { unsafe { ffi::compress_free(self.ctx); } }}
// Ensure the wrapper is safe to send between threads if the C library is thread-safeunsafe impl Send for Compressor {}
#[derive(Debug)]pub enum CompressionError { Failed,}The wrapper encapsulates all unsafe code. Users interact with Compressor through safe methods. The Drop implementation ensures the C context is freed when the Rust wrapper goes out of scope. The Option return from new() handles allocation failure. The Result return from compress () handles compression failure. Error codes become proper Rust error types.
This pattern, wrapping C resources in Rust types with RAII semantics, provides memory safety guarantees that the C library alone cannot offer. The unsafe code is concentrated in the wrapper module, tested thoroughly, and hidden from library users.
Boundaries Crossed
Unsafe Rust provides controlled access to operations the compiler cannot verify: dereferencing raw pointers, calling foreign functions, accessing mutable statics, and implementing unsafe traits. The unsafe keyword marks exactly where these operations occur, concentrating risk and simplifying audits.
Unsafe blocks enable specific operations within a limited scope; unsafe functions shift verification responsibility to callers. Raw pointers offer direct memory access without borrow checker oversight. Creating them is safe; dereferencing requires unsafe.
FFI enables calling C libraries and exposing Rust to other languages. External functions are declared in extern “C” blocks. The std::ffi module provides cross-language types. Calling foreign functions requires unsafe because Rust cannot verify their behavior.
Exposing Rust to other languages uses #[no_mangle] and extern “C”. Error handling requires translation to C-compatible patterns. Memory ownership across FFI boundaries needs explicit documentation and paired allocation/deallocation functions.
Mixed codebases require attention to build integration, memory ownership conventions, and callback patterns. Wrapping C libraries in safe Rust interfaces concentrates unsafe code in well-tested modules while providing idiomatic APIs to library users.
The next chapter explores serialization with Serde, Rust’s powerful framework for converting data structures to and from formats like JSON, YAML, and binary representations.