Skip to content

Lesson 6 of 9 · 26m

FFI and Memory Boundaries: Ownership Across Languages

Cross C boundaries with explicit ownership rules, ABI-safe types, panic containment, and defensive validation on both sides.

Most unsafe Rust in production is not exotic lock-free wizardry. It is FFI: a C library, an operating system API, a kernel structure, a driver interface, or a stable ABI plugin. The hard part is rarely calling the function. The hard part is deciding who owns what, for how long, under which threading rules, and what happens when a panic or error crosses the boundary.

Define ownership before writing bindings

Write the contract in prose first:

compressor_create returns an owned pointer; caller must free with compressor_destroy
compressor_write borrows input for the duration of the call only
compressor_output returns a pointer valid until the next compressor call
compressor objects are not thread-safe

Then encode as much of that contract as Rust types allow. Owned opaque handles deserve Rust wrapper types with Drop. Borrowed output deserves lifetimes tied to the owner. Thread restrictions affect Send and Sync; do not implement them casually.

A minimal safe wrapper

use std::os::raw::{c_int, c_void};

extern "C" {
    fn sensor_init() -> *mut c_void;
    fn sensor_read(handle: *mut c_void, out: *mut f64) -> c_int;
    fn sensor_destroy(handle: *mut c_void);
}

pub struct Sensor(*mut c_void);

impl Sensor {
    pub fn new() -> Option<Self> {
        let ptr = unsafe { sensor_init() };
        (!ptr.is_null()).then_some(Self(ptr))
    }

    pub fn read(&mut self) -> Result<f64, Error> {
        let mut value = 0.0;
        let rc = unsafe { sensor_read(self.0, &mut value) };
        if rc == 0 { Ok(value) } else { Err(Error::Sensor(rc)) }
    }
}

impl Drop for Sensor {
    fn drop(&mut self) {
        unsafe { sensor_destroy(self.0) }
    }
}

The wrapper makes the raw pointer private, ties destruction to ownership, and converts return codes into Result. The caller never signs up for unsafe obligations they cannot see.

Do not panic across FFI

Unwinding into C is undefined behavior unless the ABI explicitly supports it. At exported boundaries, catch or avoid panics and return error codes:

#[no_mangle]
pub extern "C" fn plugin_probe() -> i32 {
    match std::panic::catch_unwind(real_probe) {
        Ok(true) => 0,
        Ok(false) => 1,
        Err(_) => 2,
    }
}

Better still, validate inputs before reaching states that can panic. FFI callers are not Rust callers; they do not know your type invariants.

ABI reality bites

Only use ABI-stable representations across the boundary: C integers, opaque pointers, plain-old-data structs with #[repr(C)], and explicitly owned buffers. Rust String, Vec<T>, trait objects, enums with payload, and slices do not have a stable C ABI as-is. Convert at the boundary.

Length units deserve special suspicion. Is the length bytes or elements? Does it include a trailing NUL? Who frees it? Is it aligned enough for the type being cast? Write those answers down and test mismatches.

Field notes

  • extern crate binding generators save time, but generated bindings are not safe abstractions; wrap them.
  • Null is input validation, not a personality trait. Check it once at the boundary.
  • If C can invoke a Rust callback while Rust is dropping state, the lifecycle design is already inverted.
  • Test shutdown and error paths. FFI bugs love partially initialized objects and double-free edge cases.

Was this lesson helpful?

Sign in to rate