Build, unsafe, FFI and threads · 14 min · free lesson

unsafe, Raw Pointers and FFI

Raw pointers, unsafe and extern "C" let Rust do what C does, and unsafe marks exactly where you take over the proof that the compiler cannot do.

Core idea

Creating a raw pointer is safe; dereferencing it needs unsafe, which is a claim that the pointer is valid, aligned, initialised and correctly aliased, not a switch that turns the checks off.

C and Rust, side by side

C The pointer-and-length contract and the struct layout are stated only in comments.
#include <stdint.h>
#include <stdio.h>

struct pair {          /* C layout: tag, 3 padding bytes, value */
    uint8_t tag;
    uint32_t value;
};

/* The caller promises xs points to n readable int32_t values. */
int32_t sum_i32(const int32_t *xs, size_t n) {
    int32_t total = 0;
    for (size_t i = 0; i < n; i++) total += xs[i];
    return total;
}

int main(void) {
    int32_t xs[] = {1, 2, 3};
    struct pair p = {7, 42};
    printf("%d size=%zu tag=%u value=%u\n", sum_i32(xs, 3), sizeof p, p.tag, p.value);
    return 0;
}
Rust #[repr(C)] keeps C's layout, sum_i32 turns a pointer and a length into a slice inside one documented unsafe block, and abs comes from the C library.
use std::slice;

#[repr(C)] // C field order and padding: tag, 3 padding bytes, value
struct Pair {
    tag: u8,
    value: u32,
}

/// # Safety
/// `xs` must be non-null, aligned and point to `n` initialised `i32`s
/// that nothing mutates during the call.
unsafe extern "C" fn sum_i32(xs: *const i32, n: usize) -> i32 {
    // SAFETY: the caller upholds the contract documented above.
    let values = unsafe { slice::from_raw_parts(xs, n) };
    values.iter().sum() // from here on: ordinary, bounds-checked Rust
}

unsafe extern "C" {
    fn abs(x: i32) -> i32; // from the C library; the declaration is a promise
}

fn main() {
    let xs = [1, 2, 3];
    let p = Pair { tag: 7, value: 42 };
    // SAFETY: `xs` is a live array of 3 `i32`s, and `abs` has this C signature.
    let (total, magnitude) = unsafe { (sum_i32(xs.as_ptr(), xs.len()), abs(-5)) };
    println!("{total} size={} tag={} value={} abs={magnitude}", size_of::<Pair>(), p.tag, p.value);
}
What changes
CRust
Every pointer dereference is trusted.Only operations inside unsafe are trusted; everything else stays checked.
The contract of (ptr, n) is prose.# Safety docs and // SAFETY: comments mark the proof at each unsafe.
Struct layout follows the C ABI.Rust may reorder fields; #[repr(C)] requests C layout.

Understand it

Everything in C is the programmer's proof: the pointer is valid, n is the real length, nothing else writes meanwhile. Rust keeps that model available. *const T and *mut T are raw pointers with no lifetime and no aliasing guarantees, and creating one with as or as_ptr() is safe, because nothing can go wrong until it is used.

Dereferencing a raw pointer, calling an unsafe fn (every foreign function is one), accessing a mutable static and reading a union field need an unsafe block; implementing an unsafe trait needs unsafe impl. Inside the block the compiler still applies every other rule, including type checks, borrow checks and slice bounds checks. What unsafe adds is your claim that the invariants it cannot check hold. Write that claim down: a # Safety section on an unsafe fn lists the caller's obligations, and a // SAFETY: comment on a block says why they are met.

The common pattern is a thin unsafe edge around safe code. slice::from_raw_parts(ptr, len) turns a C pointer and length into a &[i32], and from then on indexing is checked again. The obligations of that one call are exactly what the C contract said in prose: non-null, aligned, len initialised elements, and no mutation while the slice is in use.

For FFI, #[repr(C)] gives a struct C's field order and padding for the target, so Pair is 8 bytes like struct pair; without it, Rust may reorder fields. It does not make the field types themselves C-compatible or make pointers valid. In edition 2024, foreign declarations go in an unsafe extern "C" { ... } block, and a Rust function exported to C is an extern "C" fn marked #[unsafe(no_mangle)]. Calling C needs unsafe because the compiler cannot check the declaration against the C side.

The C habit, written in Rust

This is how the C version usually looks on a first attempt in Rust. Predict what rustc says before you read the explanation.

fn main() {
    let x = 5;
    let p = &x as *const i32; // creating a raw pointer is safe
    let y = *p;               // dereferencing it is not
    println!("{y}");
}

Practise this code in Playground ↗

Try it

Decide which line of the quiz needs unsafe and what that block asserts, then fix the practice program without changing what it prints.

What success looks like: You can name the one operation that needs unsafe and the facts the block asserts about the pointer: non-null, aligned, pointing to a live, initialised value.

Check your understanding

In let p = &x as *const i32; let q = p.wrapping_add(1); let v = *p; println!("{p:?} {q:?}");, which operation needs unsafe, and what does the block claim?

Reveal the answer
  1. *p: the block claims p is non-null, aligned and points to a live, initialised i32
  2. Creating p: a raw pointer turns off the borrow checker
  3. p.wrapping_add(1) and *p: all raw pointer arithmetic is unsafe
  4. Every line: inside unsafe the compiler skips its checks

Creating a raw pointer, offsetting it with wrapping_add and printing it are safe. Only the dereference relies on facts the compiler cannot check.

Go deeper

Common misconception: “Inside unsafe, Rust behaves like C and checks nothing.”

Types, borrows and slice bounds are still checked inside unsafe. The block only permits a few extra operations, such as dereferencing a raw pointer or calling an unsafe fn, and makes you responsible for their preconditions.

  1. Find the obligations: For each unsafe operation, write down the conditions it needs, taken from its # Safety documentation.
  2. Shrink the block: Keep only the operation that needs unsafe inside the block, and convert to a safe type such as a slice as early as possible.
  3. Document the proof: Add a // SAFETY: comment that says why each condition holds at this call.

Transfer challenge: Export sum_i32 to C as #[unsafe(no_mangle)] pub unsafe extern "C" fn, write the matching C prototype, and list which # Safety conditions the C caller must now uphold.

Connections

  • Headers and make to Cargo: Modules, pub and the crate as the build unit
  • pthreads to std::thread: Locks that own data, threads that own their captures
Side-by-side comparison: the C version on the left, the Rust version on the right, then 3 rows naming what changes.
unsafe, Raw Pointers and FFI: the same task in C and in Rust, with the differences that matter.
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: unsafe, Raw Pointers and FFI (courseId "rust-for-c-developers", lessonId "c-unsafe-and-ffi")
Link: https://crabrix.com/learn/rust-for-c-developers/c-unsafe-and-ffi/
Goal: Creating a raw pointer is safe; dereferencing it needs unsafe, which is a claim that the pointer is valid, aligned, initialised and correctly aliased, not a switch that turns the checks off.
Practice: open the starter in the Crabrix Playground (https://crabrix.com/playground/?lesson=rust-for-c-developers/c-unsafe-and-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.