Engineering Craft · 21 min · free lesson

FFI and ABI

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

Core idea

repr(C) fixes layout; ownership across the boundary is documentation you enforce.

A Rust wrapper sends a pointer and length across a foreign boundary while upholding ABI, layout, readable-memory and lifetime contracts.
A foreign declaration does not validate pointer arguments; a matching implementation and explicit safety contract remain necessary.

Understand it

extern "C" fixes the calling convention, repr(C) fixes the layout, and everything about ownership becomes a convention you have to document. Who frees this pointer, may it be null, how long is it valid, and is it aliased are the four questions each call has to answer — and the safe wrapper you write around it is where those answers are enforced.

An FFI call joins two type systems at an ABI boundary. extern "C" selects the C calling convention, and #[repr(C)] requests a compatible struct layout for the target, including padding. The declarations on both sides must agree on integer widths, pointer types, alignment, and ownership. The Rust compiler cannot inspect a C header during an ordinary extern call to prove the declaration matches. A successful trivial call does not validate every edge case.

Take a function accepting a pointer and length. Ask whether the pointer may be null when length is zero, whether the callee reads or writes, whether it retains the pointer, and who frees the allocation. If Rust owns the buffer, it must remain alive throughout the foreign use. If C allocates a result, free it with the matching allocator specified by that API, not automatically with Rust's allocator. Wrap the unsafe call in a narrow function that checks lengths and translates error codes into Result.

For an interview, draw one value crossing the boundary and back. Include callback lifetime and thread assumptions if the C library calls into Rust later. Avoid exposing raw pointers to the rest of an application unless necessary. Test against the actual compiled library on each supported target, with boundary values and failures. The important point is the contract you can enforce on the Rust side and the assumptions you must trust on the foreign side.

Versioning is part of the boundary. A C library update can change a struct or function signature while Rust declarations remain stale. Compare headers and generated bindings against the linked library version in release checks. Keep opaque C types opaque on the Rust side when layout is not meant to be public.

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.

Interview follow-up: What changes if the foreign function retains the pointer after returning? Specify who allocates, who frees and which allocator is used.

Read the code

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

unsafe extern "C" {
    fn c_len(ptr: *const u8, len: usize)
        -> usize;
}

Declaration fragment: a matching C implementation and a validated wrapper are required before calling c_len; this is not a standalone linked program.

Practice starter

// Declaration fragment: a matching foreign c_use implementation is required.
use std::ffi::{CString, c_char};
unsafe extern "C" { fn c_use(value: *const c_char); }
fn main() {
    let name = CString::new("crab").unwrap();
    let ptr = name.as_ptr();
    drop(name);
    // Do not execute: unsafe { c_use(ptr) }; would use a dangling pointer.
}

Practise this code in Playground ↗

Try it

Wrap one C function so no safe caller can misuse it.

What success looks like: Null, lifetime, and ownership are all handled inside the wrapper.

Check your understanding

Why is this raw pointer invalid after the CString is dropped?

Reveal the answer
  1. Calling as_ptr transfers the CString buffer to the foreign function.
  2. The pointer does not own the buffer or extend the CString allocation’s lifetime.
  3. Using extern C makes every pointer valid until the process exits.

Keep the owner alive for the entire foreign use, or use an explicit ownership-transfer API with a matching release contract. repr(C) alone does not establish pointer validity.

Go deeper

Common misconception: Using extern C makes every pointer valid until the process exits.

extern "C" fixes the calling convention only. It says nothing about pointer lifetime, so this pointer dangles as soon as name is dropped.

  1. Identify the contract: FFI needs explicit ABI, layout, ownership and validity contracts; unsafe code must uphold the foreign function requirements.
  2. Trace the concrete example: Declaration fragment: a matching C implementation and a validated wrapper are required before calling c_len; this is not a standalone linked program.
  3. Test the changed constraint: What changes if the foreign function retains the pointer after returning? Specify who allocates, who frees and which allocator is used.

Transfer challenge: What changes if the foreign function retains the pointer after returning? Specify who allocates, who frees and which allocator is used.

Connections

  • Profiling First: Measure, change one thing, measure
  • Live Coding: Two Sum: Clarify duplicates, indices, and complexity first
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 and ABI (courseId "interview", lessonId "q-ffi-abi")
Link: https://crabrix.com/learn/interview/q-ffi-abi/
Goal: repr(C) fixes layout; ownership across the boundary is documentation you enforce.
Practice: open the starter in the Crabrix Playground (https://crabrix.com/playground/?lesson=interview/q-ffi-abi) 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.