Skip to content
RustLearn

Module 19 — Macros, Unsafe & FFI

Goal

Code that writes code with macro_rules! and derive macros, the five superpowers of unsafe, and calling C from Rust (and back).

Start here — what this module is really about

Three advanced topics with one thing in common: each hands you power the ordinary language withholds, and each comes with a responsibility attached.

Macros — code that writes code. A function takes values and returns a value. A macro takes code and produces code, before type checking begins. That is why println! can validate your format string at compile time, why vec![1, 2, 3] can accept any number of arguments when no function could, and why #[derive(Debug)] can write an entire implementation for you. The ! you have been typing since module 01 has always meant this.

unsafe — five specific operations. This one is widely misunderstood, so be precise: unsafe does not switch off the borrow checker, and it does not make the rest of your program unchecked. It unlocks exactly five things the compiler cannot verify — chiefly dereferencing raw pointers and calling foreign functions — and transfers responsibility for their correctness from the compiler to you. Every guarantee still holds everywhere else.

FFI — calling C, and being called by C. Two languages that share no memory model, no ownership rules and no guarantees. Crossing between them means restating everything in terms both sides understand, and accepting that Rust's promises stop at the boundary.

The through-line: all three are for library authors and specific situations. Most excellent Rust is written without ever typing unsafe, and macros are worth reaching for only when a function genuinely cannot do the job. Knowing they exist and how to read them matters more than using them.

The one sentence to remember: macros generate code before compilation, unsafe unlocks five checked-by-you operations rather than disabling safety, and FFI is a border crossing where Rust's guarantees end.

Learning objectives

  • Write declarative macros with macro_rules!
  • Understand the three kinds of procedural macros
  • Know exactly what unsafe does and does not disable
  • Use raw pointers and unsafe blocks responsibly
  • Call C from Rust and expose Rust to C

Part A — Macros

19.1 Why macros

Macros generate code at compile time. Reach for one when a function cannot do the job:

  • Variable arity: println!, vec!, format!
  • Compile-time validation: format-string checking
  • Generating trait impls: #[derive(Debug)]
  • New syntax: matches!, tokio::select!

Cost: harder to read, harder to debug, worse IDE support, slower compiles. A function is almost always better. Write a macro when you've written the same boilerplate three times and there's no generic way out.

Analogy — the stamp that prints the form

A function takes values and returns a value. A macro takes code and returns code — it is the office stamp that prints a whole pre-filled form where you pressed it. That is why println! can check its format string at compile time and why vec![] can take any number of arguments: by the time the compiler type-checks anything, the stamp has already printed ordinary Rust.

19.2 macro_rules!

rust
macro_rules! say_hello {
    () => {
        println!("Hello!");
    };
}

say_hello!();

A macro is a set of (pattern) => {expansion} rules matched against token trees.

Fragment specifiers

rust
macro_rules! demo {
    ($e:expr) => { ... };      // expression
    ($i:ident) => { ... };     // identifier
    ($t:ty) => { ... };        // type
    ($p:pat) => { ... };       // pattern
    ($s:stmt) => { ... };      // statement
    ($b:block) => { ... };     // { ... }
    ($l:literal) => { ... };   // literal
    ($p:path) => { ... };      // a::b::C
    ($t:tt) => { ... };        // any single token tree — the escape hatch
}

Repetition

rust
macro_rules! my_vec {
    () => { Vec::new() };
    ($($x:expr),+ $(,)?) => {
        {
            let mut v = Vec::new();
            $( v.push($x); )+
            v
        }
    };
}

let v: Vec<i32> = my_vec![1, 2, 3,];

Repetition syntax: $( ... ),* (zero or more, comma-separated), $( ... );+ (one or more, semicolon-separated), $(,)? (optional trailing comma).

A genuinely useful example

rust
use std::collections::HashMap;

macro_rules! hashmap {
    ($($key:expr => $value:expr),* $(,)?) => {{
        let mut map = HashMap::new();
        $( map.insert($key, $value); )*
        map
    }};
}

fn main() {
    let scores = hashmap! {
        "alice" => 90,
        "bob"   => 85,
    };
    println!("{scores:?}");
}

Generating impls

rust
macro_rules! impl_describe {
    ($($t:ty => $name:expr),* $(,)?) => {
        $(
            impl Describe for $t {
                fn describe(&self) -> String {
                    format!("{} with value {}", $name, self)
                }
            }
        )*
    };
}

trait Describe { fn describe(&self) -> String; }

impl_describe! {
    i32 => "an integer",
    f64 => "a float",
    bool => "a boolean",
}

Hygiene

Macros are hygienic for local variables: an identifier introduced inside the macro cannot capture or be captured by one at the call site.

rust
macro_rules! using_a {
    ($e:expr) => { { let a = 42; $e } };
}

let a = 10;
println!("{}", using_a!(a));    // 10 — the macro's `a` is a different variable

This is a major improvement over C's textual #define.

Debugging macros

bash
cargo install cargo-expand
cargo expand              # shows the code after macro expansion

Also useful: trace_macros!(true) on nightly.

Reading a macro_rules! definition

Macro syntax looks alien mostly because it has its own small pattern language. Here is a complete one, annotated:

rust
macro_rules! my_vec {
    () => {                                  // pattern 1: no arguments
        Vec::new()
    };
    ($($item:expr),+ $(,)?) => {             // pattern 2: one or more expressions
        {
            let mut v = Vec::new();
            $( v.push($item); )+             // repeat this once per matched item
            v
        }
    };
}

let empty: Vec<i32> = my_vec![];
let nums = my_vec![1, 2, 3];

The pieces:

  • A macro is a list of rules, each pattern => expansion, tried in order — much like a match, but over syntax rather than values.
  • $item:expr captures a fragment and names it. The part after the colon is the fragment type, saying what kind of syntax is allowed there: expr (an expression), ident (a name), ty (a type), stmt, block, literal, path, tt (any token tree).
  • $( ... ),+ means "one or more of these, separated by commas". Inside the expansion, $( ... )+ repeats the body once per captured item. * means zero or more; $(,)? allows an optional trailing comma.
  • The extra braces in the expansion make it a single block expression, so the macro can be used anywhere a value is expected.

One property worth knowing: macros are hygienic. A variable named v inside the macro cannot collide with a v at the call site — the compiler keeps them distinct. That is a real improvement on C's textual macros, where exactly that collision is a classic bug.

19.3 Procedural macros

Proc macros are Rust programs that take a TokenStream and return a TokenStream. They live in a separate crate marked proc-macro = true.

Three kinds:

rust
#[derive(MyTrait)]                 // derive macro
#[route(GET, "/")]                 // attribute macro
sql!(SELECT * FROM users)          // function-like macro

A minimal derive macro:

toml
# my_macro/Cargo.toml
[lib]
proc-macro = true

[dependencies]
syn = "2"
quote = "1"
proc-macro2 = "1"
rust
use proc_macro::TokenStream;
use quote::quote;
use syn::{parse_macro_input, DeriveInput};

#[proc_macro_derive(HelloMacro)]
pub fn hello_macro_derive(input: TokenStream) -> TokenStream {
    let ast = parse_macro_input!(input as DeriveInput);
    let name = &ast.ident;

    let expanded = quote! {
        impl HelloMacro for #name {
            fn hello_macro() {
                println!("Hello, Macro! My name is {}!", stringify!(#name));
            }
        }
    };
    expanded.into()
}

Usage:

rust
#[derive(HelloMacro)]
struct Pancakes;

Pancakes::hello_macro();

syn parses Rust into an AST; quote! builds Rust from a template with #var interpolation. This is how serde, thiserror, clap, and tokio::main work. Writing proc macros is a substantial subfield — the point here is to recognize what they are when you see them.


Part B — Unsafe Rust

19.4 What unsafe actually means

unsafe does not turn off the borrow checker or type checking. It enables exactly five extra abilities:

  1. Dereference a raw pointer
  2. Call an unsafe function or method
  3. Access or modify a mutable static
  4. Implement an unsafe trait
  5. Access fields of a union

Everything else — ownership, borrowing, lifetimes, type safety — still applies. unsafe means "I have verified the invariants the compiler cannot check here."

What unsafe does and does not do

The single most important table in this module:

unsafe does let youunsafe does not turn off
Dereference a raw pointerThe borrow checker
Call an unsafe function, including foreign onesType checking
Access or modify a mutable staticOwnership and moves
Implement an unsafe traitLifetime checking
Access fields of a unionAnything else, anywhere

So an unsafe block is not a lawless region. It is a statement that you have personally verified the five things the compiler cannot.

What good practice looks like:

rust
/// Returns the element at `index`.
///
/// # Safety
/// The caller must ensure `index < self.len()`. Passing an out-of-range
/// index reads memory outside the allocation.
pub unsafe fn get_unchecked(&self, index: usize) -> &T {
    unsafe { &*self.ptr.add(index) }
}

Three habits that make unsafe code reviewable:

  1. Keep the block as small as the operation. Two lines inside a safe function, not a whole function marked unsafe.
  2. Write the # Safety section. It is not documentation etiquette — it is the contract stating precisely what the caller must guarantee. Rust's own standard library does this everywhere.
  3. Wrap it in a safe API (§19.6). Users of your crate should get an ordinary safe function whose implementation upholds the invariants internally.

And run cargo miri test (§19.9) on anything containing unsafe. It detects undefined behaviour that ordinary tests sail straight past.

Analogy — the key to the plant room

unsafe does not switch off the compiler's checks on your programme; it unlocks five specific operations the compiler cannot verify, and transfers responsibility for their rules onto you. It is the key to the plant room, not permission to ignore the fire code — and the block should be as small as the job, with the invariants you are now personally guaranteeing written above it.

19.5 Raw pointers

rust
let mut num = 5;

let r1 = &num as *const i32;      // immutable raw pointer
let r2 = &mut num as *mut i32;    // mutable raw pointer

unsafe {
    println!("r1 is: {}", *r1);
    *r2 = 10;
    println!("r2 is: {}", *r2);
}

Raw pointers can be null, dangling, unaligned, and can alias mutably — all the things references cannot. Creating one is safe; dereferencing it is not.

rust
let address = 0x012345usize;
let r = address as *const i32;
// unsafe { println!("{}", *r); }   // 💥 undefined behaviour

19.6 Safe abstractions over unsafe code

The idiomatic pattern: a small unsafe core with a safe public API whose invariants you can prove.

rust
use std::slice;

fn split_at_mut(values: &mut [i32], mid: usize) -> (&mut [i32], &mut [i32]) {
    let len = values.len();
    let ptr = values.as_mut_ptr();
    assert!(mid <= len);

    unsafe {
        (
            slice::from_raw_parts_mut(ptr, mid),
            slice::from_raw_parts_mut(ptr.add(mid), len - mid),
        )
    }
}

The compiler can't prove the two slices are disjoint, but we can: mid <= len is asserted, and the ranges [0, mid) and [mid, len) don't overlap. The function is safe to call with any arguments, so it needs no unsafe in its signature.

This is what Vec, RefCell, Mutex, and most of the standard library are: safe APIs built on carefully audited unsafe internals.

Analogy — the sealed appliance

Good unsafe code is a sealed appliance: dangerous voltages inside, an ordinary switch outside, and a safety certificate stating exactly the conditions under which the seal holds. Users of your crate get the safe switch. Anyone opening the case reads the certificate first — which is why the # Safety comment is not documentation etiquette, it is the certificate.

19.7 unsafe fn and documenting invariants

rust
/// # Safety
///
/// `ptr` must be non-null, aligned, and point to `len` initialized `T` values that
/// remain valid and unaliased for the duration of `'a`.
unsafe fn from_raw<'a, T>(ptr: *const T, len: usize) -> &'a [T] {
    slice::from_raw_parts(ptr, len)
}

Every unsafe fn must have a # Safety section stating the caller's obligations. Clippy enforces this (clippy::missing_safety_doc).

19.8 Mutable statics — avoid

rust
static mut COUNTER: u32 = 0;

fn add(inc: u32) {
    unsafe { COUNTER += inc; }     // data race waiting to happen
}

Every access needs unsafe because concurrent access is a data race. Modern alternatives:

rust
use std::sync::atomic::{AtomicU32, Ordering};
static COUNTER: AtomicU32 = AtomicU32::new(0);
COUNTER.fetch_add(1, Ordering::SeqCst);

use std::sync::{LazyLock, Mutex};
static CONFIG: LazyLock<Mutex<Vec<String>>> = LazyLock::new(|| Mutex::new(Vec::new()));

19.9 Tooling for unsafe code

bash
cargo +nightly miri test      # interpreter that detects UB in tests
cargo install cargo-geiger    # counts unsafe usage in your dependency tree
RUSTFLAGS="-Z sanitizer=address" cargo +nightly test

Miri catches out-of-bounds access, use-after-free, misaligned reads, and data races in test runs. If you write unsafe code, run Miri.


Part C — FFI

19.10 Calling C from Rust

rust
extern "C" {
    fn abs(input: i32) -> i32;
    fn sqrt(x: f64) -> f64;
}

fn main() {
    unsafe {
        println!("{}", abs(-3));        // 3
        println!("{}", sqrt(2.0));
    }
}

Every foreign call is unsafe because Rust cannot verify the other side's contract.

With a real C library, use bindgen to generate the declarations:

toml
[build-dependencies]
bindgen = "0.69"
rust
// build.rs
fn main() {
    println!("cargo:rustc-link-lib=mylib");
    let bindings = bindgen::Builder::default()
        .header("wrapper.h")
        .generate()
        .expect("unable to generate bindings");
    bindings.write_to_file(
        std::path::PathBuf::from(std::env::var("OUT_DIR").unwrap()).join("bindings.rs")
    ).unwrap();
}

C strings

rust
use std::ffi::{CStr, CString};
use std::os::raw::c_char;

extern "C" { fn puts(s: *const c_char) -> i32; }

fn main() {
    let msg = CString::new("hello from rust").unwrap();
    unsafe { puts(msg.as_ptr()); }
}

CString is NUL-terminated and rejects interior NULs; String is UTF-8 and length-prefixed. They are not interchangeable, which is why conversion is explicit.

Crossing to C, and what stops at the border

rust
use std::os::raw::c_int;

// Declare what exists on the other side.
unsafe extern "C" {
    fn abs(input: c_int) -> c_int;
}

fn main() {
    // The call is unsafe: Rust cannot check C's behaviour.
    let n = unsafe { abs(-3) };
    println!("{n}");
}

Everything that must be restated at the boundary, because C shares none of it:

  • Memory layout. Rust may reorder struct fields; C may not. Any struct crossing the boundary needs #[repr(C)] to guarantee C's layout.
  • Ownership. C has no idea who frees what. Every allocation crossing the boundary needs an explicit, documented convention about which side releases it.
  • Strings. Rust strings are UTF-8 with a length; C strings are bytes terminated by a zero. Convert with CString (going out) and CStr (coming in). Handing a Rust String to C directly is a bug.
  • Errors. No Result, no panics — C returns codes. And a Rust panic must never unwind across the boundary; catch it on your side.

The discipline that keeps this manageable is the same as with unsafe: cross in as few places as possible, and wrap each crossing in a safe Rust API so the rest of your program never sees a raw pointer.

Analogy — the stamp that prints the form

A function takes values and returns a value. A macro takes code and returns code — it is the office stamp that prints a whole pre-filled form where you pressed it. That is why println! can check its format string at compile time and why vec![] can take any number of arguments: by the time the compiler type-checks anything, the stamp has already printed ordinary Rust.

Analogy — the interpreter at the border

C and Rust do not share a language, a memory model or a set of guarantees. FFI is a border crossing with an interpreter: everything must be restated in terms both sides accept (repr(C), raw pointers, explicit lengths), and every assurance Rust made about lifetimes and ownership stops at the line. Cross deliberately, in as few places as possible, and wrap each crossing in a safe abstraction on the Rust side.

19.11 Exposing Rust to C

rust
#[no_mangle]
pub extern "C" fn rust_add(a: i32, b: i32) -> i32 {
    a + b
}

#[no_mangle]
pub extern "C" fn rust_greet(name: *const c_char) -> *mut c_char {
    let name = unsafe { CStr::from_ptr(name) }.to_string_lossy();
    CString::new(format!("Hello, {name}!")).unwrap().into_raw()
}

/// # Safety
/// `s` must be a pointer previously returned by `rust_greet`.
#[no_mangle]
pub unsafe extern "C" fn rust_free_string(s: *mut c_char) {
    if !s.is_null() { drop(CString::from_raw(s)); }
}
toml
[lib]
crate-type = ["cdylib", "staticlib"]

#[no_mangle] keeps the symbol name intact; extern "C" sets the calling convention. Note the paired allocate/free functions: memory allocated by Rust must be freed by Rust.


Analogy — the stamp that prints the form

A function takes values and returns a value. A macro takes code and returns code — it is the office stamp that prints a whole pre-filled form where you pressed it. That is why println! can check its format string at compile time and why vec![] can take any number of arguments: by the time the compiler type-checks anything, the stamp has already printed ordinary Rust.

Jargon buster

Every term this module used, in ordinary words. Nothing here is optional vocabulary — these are the words the compiler's error messages will use when talking to you.

TermIn plain English
macroCode that generates code before compilation.
declarative macroA macro_rules! macro, defined by pattern matching on syntax.
procedural macroA macro written as Rust code that transforms a token stream — how #[derive] works.
fragment specifierThe :expr, :ident, :ty part saying what syntax a capture accepts.
repetition $()*Match or generate a pattern zero or more times.
hygieneMacro-internal names cannot collide with names at the call site.
unsafeUnlocks five operations the compiler cannot verify; you take responsibility.
raw pointer *const T / *mut TA pointer with no lifetime, no ownership and no guarantees.
undefined behaviourCode whose meaning the language does not define. Anything may happen.
safe abstractionA safe public API whose implementation contains carefully audited unsafe code.
# SafetyThe doc section stating what a caller must guarantee.
FFIForeign Function Interface — calling across a language boundary.
extern "C"Use the C calling convention.
#[repr(C)]Lay this type out the way C would.
CString / CStrOwned and borrowed null-terminated C strings.
MiriAn interpreter that detects undefined behaviour in unsafe code.

If you get stuck

The errors this module actually produces, what each one means, and what to do about it. Find yours here before searching anywhere else.

What you seeWhat it meansWhat to do
error[E0133]: call to unsafe function is unsafeYou called an unsafe function outside an unsafe block.Wrap it — and write down why it is sound.
no rules expected this token in macro callYour call does not match any of the macro's patterns.Compare against the patterns; usually a separator or a missing fragment.
error: macro expansion ignores tokenThe expansion produced syntax that does not fit where it was used.Wrap the expansion in braces so it is one block expression.
Segfault or nonsense valuesUndefined behaviour from unsafe code.Run cargo miri test. Check every pointer's validity and alignment.
error: linking with cc failedThe C library was not found or not built.Check build.rs, the link name, and that the library exists on the system.
Garbled strings across FFIA Rust string was passed where C expected null termination.Convert with CString; never hand over a String directly.

Now make it stick: work through the drills for this module, then carry on to Module 20 — Idioms, Performance & Capstones.