On this page
  1. unsafe Rust & C ABI FFI
  2. Contents
  3. The Five unsafe Superpowers
  4. #[repr(C)] & Sound FFI Boundaries

unsafe Rust & C ABI FFI

Prev: Enums, Pattern Matching & Error Propagation | Up: ownership_and_internals | Next: cargo_and_tooling
Rel: unsafe, rust/std/ffi, C Build Pipeline & ABI, PyO3
Ref: The Rustonomicon — FFI
Tags: #public #prog #rust #internals #unsafe #ffi


Contents


The Five unsafe Superpowers

unsafe does not disable the borrow checker — it only unlocks five operations the compiler cannot statically prove sound:

  1. Dereferencing raw pointers (*const T, *mut T).
  2. Calling an unsafe fn or extern "C" foreign function.
  3. Accessing or modifying a static mut variable.
  4. Implementing an unsafe trait (e.g., Send, Sync).
  5. Reading fields of a union.

#[repr(C)] & Sound FFI Boundaries

Rust's default struct layout (#[repr(Rust)]) may reorder fields freely. Always annotate FFI structs with #[repr(C)], validate pointers for null/alignment at the boundary, and never let a Rust panic! unwind across extern "C" (catch with std::panic::catch_unwind or return error codes).

#[repr(C)]
pub struct Vec2 {
    pub x: f64,
    pub y: f64,
}

#[unsafe(no_mangle)]
pub extern "C" fn vec2_len(v: Vec2) -> f64 {
    (v.x * v.x + v.y * v.y).sqrt()
}

Linked from

Related notes