skip to content

Foreign Function Calls

FFI declares C functions in an unsafe extern block and passes data in C layout. Interviewers ask who frees memory across the boundary and what happens when a panic reaches C.

on this pageshow

questions

6

In Rust 2024, how do you declare and call a C function such as `strlen`, and why does the call need `unsafe`?

level: juniorimportance: must knowfreq 55%

answer

  1. a block of foreign signatures
  2. a keyword before extern
  3. rustc never sees the C body
  4. safe or unsafe per item

basics

~20 s

Declare the C signature inside an unsafe extern "C" block and call it inside an unsafe block: rustc cannot check foreign code, so the caller vouches for its preconditions. An item declared safe fn needs no unsafe block.

solid answer

~50 s

You write `unsafe extern "C" { fn strlen(s: *const c_char) -> usize; }` and the linker resolves `strlen` from the C library. The `unsafe` on the block is the author's promise that every signature matches the real C definition, because a wrong one is undefined behaviour that nothing checks; since the 2024 edition rustc rejects a block without it (`error: extern blocks must be unsafe`). Items in the block are unsafe to call by default, so `strlen(p)` goes inside an `unsafe { }` block where you uphold its contract: `p` is non-null and NUL-terminated. Since Rust 1.82 an item can be declared `safe fn` when no argument can make it misbehave, like `abs(c_int)`, and is then called like ordinary Rust. Parameter types come from `std::ffi` (`c_char`, `c_int`, `c_void`) so they match the platform's C types.

code

rust · 16 lines
rust
use std::ffi::{c_char, c_int, CStr};

unsafe extern "C" {
    // Any i32 is a valid input, so the declaration can promise safety.
    safe fn abs(x: c_int) -> c_int;
    // Needs a valid, NUL-terminated pointer: stays unsafe to call.
    fn strlen(s: *const c_char) -> usize;
}

fn main() {
    let n = abs(-7); // no unsafe block: declared `safe`
    let s: &CStr = c"compress";
    // SAFETY: `s` is a valid NUL-terminated string that outlives the call.
    let len = unsafe { strlen(s.as_ptr()) };
    println!("abs = {n}, strlen = {len}");
}

go deeper

for a junior

Recall the shape: signatures in an unsafe extern "C" block, calls inside an unsafe block, C types from std::ffi. Say plainly that rustc cannot see or check the C code.

for a middle

Explain the two promises: the block's author vouches for the signatures, the caller vouches for each call's preconditions. Know that items default to unsafe and that safe fn opts one out.

for a senior

Show that a mismatched signature links fine and is undefined behaviour, and that safe fn is only for functions no input can break. Keep raw declarations private behind safe wrappers that establish preconditions.

for a principal

Frame the declaration as an unchecked contract with another codebase. A team should keep that contract in one audited module, generated or checked against the real header, so it stays correct as the library changes.

## What an extern block declares Rust calls C through a **foreign function interface (FFI)**: Rust code calls a function that was compiled by a C compiler and lives in another object file or library. To do that, rustc needs a **declaration**: the function's name, its parameter and return types, and its **ABI** (application binary interface, the calling convention that says where arguments go in registers and on the stack). That declaration lives in an **extern block**: ```rust unsafe extern "C" { fn strlen(s: *const c_char) -> usize; } ``` - `"C"` is the ABI string. The Reference defines it as the default ABI of the dominant C compiler for the target. Leaving the string out also means `"C"`, but the Reference notes that form is being phased out, so write it. - The body holds declarations ending in semicolons, usually functions and sometimes statics. The code comes from whatever library the linker finds; how that library gets linked is a build-configuration matter, not something the block itself controls. - The name is matched by **symbol** at link time. Nothing compares your types with the C header. ## Why the block itself is unsafe Because rustc never sees the C definition, it cannot tell whether `strlen` really takes one pointer and returns a `size_t`. If you declare `fn strlen(s: *const c_char) -> u8` or forget a parameter, the program still compiles and links, and every call is **undefined behaviour**. The `unsafe` keyword in front of `extern` records who carries that risk: the author of the block promises the signatures are correct. The 2024 edition guide puts it the same way. The keyword stresses that the author of the extern block must make sure the signatures are correct. ## Calling: unsafe by default, safe by opt-in The Reference states that a function declared in an extern block is **implicitly unsafe** unless the `safe` qualifier is present. So there are two kinds of item: | Declared as | Call site | Use it when | |---|---|---| | `fn strlen(...)` or `unsafe fn strlen(...)` | inside `unsafe { }` | the C function has preconditions: valid pointers, lengths, initialised state | | `safe fn abs(x: c_int) -> c_int` | ordinary call | every value a safe caller can pass is fine | An unsafe call obliges the caller to meet the foreign function's contract. For `strlen`, the pointer must be non-null and point to a NUL-terminated string that stays alive for the call. The compiler enforces only the *location* of the call: without the block you get `` error[E0133]: call to unsafe function `strlen` is unsafe and requires unsafe block ``. By convention a `// SAFETY:` comment above the block says why the contract holds. Marking an item `safe` moves the proof to the declaration. It is right for `abs` or `sqrt`, wrong for anything that dereferences a pointer you pass. ## What changed, and when | Rust | `extern "C" { }` | `unsafe extern "C" { }` | `safe fn` items | |---|---|---|---| | Editions before 2024, before 1.82 | accepted | not available | not available | | Editions before 2024, 1.82 and later | accepted | accepted | only inside an `unsafe extern` block | | Edition 2024 (from 1.85) | **error**: `extern blocks must be unsafe` | required | allowed | On edition 2024, rustc 1.99 reports the old form as `error: extern blocks must be unsafe` with the help line `` needs `unsafe` before the extern keyword ``. On edition 2021, writing `safe fn` inside a plain `extern "C"` block is an error too: `` items in `extern` blocks without an `unsafe` qualifier cannot have safety qualifiers ``. ## Getting the signature right 1. **Use C types from `std::ffi`.** `c_int`, `c_long`, `c_char` and `c_void` follow the target's C definitions. Whether `c_char` is `i8` or `u8` depends on the platform, and `c_long` differs between 64-bit Windows and 64-bit Linux. 2. **Use raw pointers for C pointers.** `*const T` and `*mut T` say nothing about lifetimes or non-null-ness, which is the honest description of a C pointer. A reference in a foreign signature makes a promise you have to keep on C's behalf. 3. **Pass only FFI-safe types.** The `improper_ctypes` lint (warn by default) flags a declaration that takes a `String`, a `Vec` or a struct without a C-compatible representation. 4. **Pick the ABI on purpose.** `"C"` covers most libraries. `"system"` is for the Windows API. `"C-unwind"` is for functions that may unwind across the boundary. ## The habit interviewers listen for - Declare once, in one small module, and keep the raw items private. - Wrap each unsafe item in a safe Rust function that sets up its preconditions, for example by taking `&CStr` instead of a raw pointer. - Write a `SAFETY` comment at every unsafe call that names the contract it satisfies.

  • What happens if the declared Rust signature does not match the C function's real one?
    Nothing at build time: rustc sees only your declaration, and the linker matches the symbol by name, not by type. A wrong parameter type, a missing argument or a wrong return type compiles and links, and every call is undefined behaviour. That obligation is exactly what the `unsafe` on the block records, which is why generated bindings or a test against the real header pay off.
  • When is it right to declare an item in an `unsafe extern` block as `safe fn`?
    When no argument a safe caller can produce makes the C function misbehave, such as `abs(c_int)` or `sqrt(f64)`. A function taking a raw pointer, a pointer and a length, or one that depends on global C state usually does not qualify. Keep those unsafe and wrap them in a safe Rust function that establishes the precondition.
  • Which ABI does `unsafe extern { }` use when no ABI string is written?
    `"C"`. The Reference says the ABI defaults to C when the string is omitted, but also that the bare form is being phased out, so write `extern "C"` explicitly. Use `"system"` for Windows API functions and the `-unwind` variants only when unwinding must cross the boundary.

  • rustc checks the extern declaration against the C header.
  • Functions in an extern block are safe to call unless marked unsafe.
  • The unsafe before extern makes every call inside the block safe.
  • Edition 2024 still accepts a plain extern "C" block with only a warning.
  • Using i8 for C's char is portable to every target.

Assumes Rust 1.99 on edition 2024; unsafe extern blocks and safe items arrived in Rust 1.82, and the 2024 edition (Rust 1.85) made the unsafe keyword on extern blocks mandatory.

open as a page

A Rust wrapper for a C compression library gets C-allocated buffers back and hands Rust-allocated strings to C; who frees each, and with what?

level: seniorimportance: must knowfreq 50%

basics

~20 s

Whoever allocated frees, with the matching function. Wrap C buffers in a Rust type whose Drop calls the library's free. Strings handed out with CString::into_raw come back to an exported Rust function that calls CString::from_raw.

open as a page

In Rust, why is `let p = CString::new(name).unwrap().as_ptr();` followed by a C call a bug, and when does `CString::new` fail?

level: middleimportance: should knowfreq 50%

basics

~20 s

The CString is a temporary dropped at the end of the let statement, so p dangles before C reads it. Bind the CString to a variable that outlives the call. CString::new returns Err(NulError) when the bytes contain an interior NUL.

open as a page

In Rust 2024, what does a function need so a C program can call it by name, and what do `extern "C"` and `#[unsafe(no_mangle)]` each do?

level: middleimportance: should knowfreq 45%

basics

~10 s

extern "C" gives the function C's calling convention; #[unsafe(no_mangle)] keeps its symbol name unmangled so the C linker finds it. Any struct it passes needs #[repr(C)], and edition 2024 requires the unsafe(...) wrapper.

open as a page

A Rust progress callback passed to a C library as an `extern "C"` function panics; what happens in Rust 1.99, and how should the wrapper prevent it?

level: seniorimportance: should knowfreq 40%

basics

~20 s

Since Rust 1.81 the panic aborts the whole process at the extern "C" boundary instead of unwinding into C. The wrapper's callback should run user code inside catch_unwind and return an error code to C.

open as a page

Leading a Rust team that wraps a C compression library, would you generate the bindings with bindgen or write them by hand, and where does the safe boundary go?

level: principalimportance: should knowfreq 30%

basics

~20 s

Generate with bindgen when the header is large or changes, write by hand for a few stable functions. Either way, raw declarations sit in a thin sys layer, and a separate safe layer holds the unsafe calls, ownership and error mapping.

open as a page