Systems Rust · 21 min · free lesson

FFI

FFI needs explicit ABI, layout, ownership and validity contracts; unsafe code must uphold the foreign function requirements.

Core idea

repr(C) follows C layout rules for the target; it is not a recursive layout, ownership or pointer-validity guarantee.

Rust arguments cross a C ABI boundary with corresponding C types and an explicit borrowed buffer lifetime.
Both sides must agree on calling convention, layout, and ownership.

Understand it

extern "C" selects the C calling convention and #[repr(C)] fixes field order so a struct matches its C counterpart. Unless a declaration is marked safe fn, every call is unsafe, because the compiler cannot see the other side, and ownership must be agreed explicitly — who allocates, who frees, and how long a borrowed pointer stays valid.

An FFI boundary is a contract shared by two languages. The ABI determines how arguments and return values cross the call; #[repr(C)] helps a Rust struct follow C field order and padding rules for the target. It does not make every Rust type valid for C: String, Vec, and Rust enums without an explicit representation need a deliberate interface. Prefer fixed-width integer types where the C declaration requires them and check the target's definitions for size_t, pointers, and alignment.

In the example, abs takes and returns a C int; the Rust declaration must match the actual C header on that target. For a pointer argument, document whether the callee may write, retain the pointer, or free it. If Rust owns a buffer, keep it alive for the whole call and do not let C retain it unless the API explicitly transfers ownership. Translate C error codes or null pointers into Result or Option in a small safe wrapper. Compile a tiny cross-language test against the real library, including boundary values. Do not rely on the Rust compiler to detect a signature mismatch it cannot see. The best FFI module exposes an ordinary safe Rust API while keeping the foreign assumptions visible and auditable in one place.

Also consider callbacks crossing back into Rust. The C library may call them later, from another thread, or after shutdown. A Rust closure cannot be passed as a bare function pointer without a deliberate trampoline and context lifetime. Keep callback ownership and thread assumptions in the same contract as pointer validity. A working happy-path call proves little about those edges.

In Rust 2024, foreign declarations use unsafe extern "C" blocks; that spelling is also accepted in earlier editions. Calling a foreign function remains unsafe unless its declaration explicitly establishes otherwise. These examples require a matching linked foreign implementation and illustrate a desktop ABI boundary, not support for arbitrary native C libraries in Crabrix. For C abs, the minimum signed integer is not a valid argument when its positive magnitude cannot be represented; the fixed -42 example avoids that boundary.

#[repr(C)] on an outer struct does not change the representation of an inner field’s type. Define C-compatible representations for nested by-value data too. The resulting size, padding and alignment still depend on the target ABI; do not use an in-memory C layout as a portable file or network format. Document allocator pairing, pointer length and validity, nullability, callback lifetime and unwinding separately.

Read the code

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

unsafe extern "C" {
    fn abs(value: i32) -> i32;
}

fn main() {
    // SAFETY: -42 and its absolute value fit the C int range here.
    // The linked library must provide the declared C ABI function.
    let value = unsafe { abs(-42) };
    println!("{value}");
}

A declaration, a layout guarantee, and one unsafe call.

Practice starter

struct Point { x: f64, y: f64 }

unsafe extern "C" { fn distance(p: Point) -> f64; }

Practise this code in Playground ↗

Try it

Declare a foreign function and describe who owns any memory it returns.

What success looks like: The ownership contract is written down, not assumed.

Check your understanding

What is missing from that struct?

Reveal the answer
  1. Nothing — Rust already matches the C layout
  2. #[repr(C)] — Rust does not guarantee field order otherwise
  3. The struct has to be declared pub for the C side

Without repr(C) the layout is unspecified and the C side may read the wrong bytes. Rust's improper_ctypes lint warns about this declaration.

Go deeper

Common misconception: “Rust lays out a struct in declaration order, so it already matches C.”

repr(C) fixes layout; without it Rust may reorder fields. Declaration order is a promise only under #[repr(C)].

  1. Fix the layout: #[repr(C)] gives Point C field order and padding. Nothing in this sample passes a Point, so it shows only the layout half of the contract.
  2. Declare the function: unsafe extern "C" declares abs with the C calling convention. The signature is a claim about the real C header, and rustc cannot check it.
  3. Make the call: unsafe { abs(-42) } relies on the SAFETY comment. The linked C library returns 42, and println! shows it.

Transfer challenge: Write a safe fn c_abs(value: i32) -> Option<i32> around abs that returns None for i32::MIN. Say which input it rules out and what remains an unchecked claim about the C side.

Connections

  • unsafe Rust: Five powers and their invariants
  • Performance: Allocation, iterators, and measuring
Learn this lesson with AI

Paste this into Claude, Codex, Cursor or another agent connected to Crabrix Academy. It contains only this lesson’s public details.

I'm learning Rust with Crabrix Academy. Teach me this lesson with the Crabrix Academy tools.
Lesson: FFI (courseId "systems", lessonId "ffi")
Link: https://crabrix.com/learn/systems/ffi/
Goal: repr(C) follows C layout rules for the target; it is not a recursive layout, ownership or pointer-validity guarantee.
Practice: open the starter in the Crabrix Playground (https://crabrix.com/playground/?lesson=systems/ffi) and I will write the code there.
Explain it step by step for my level, let me write the code myself, give hints before any solution, and do not mark anything as passed: only Crabrix checks do that.

In Claude Code, Codex or Cursor, paste it into a chat with Crabrix Academy connected. On a phone, the Claude and ChatGPT apps open the same links.