skip to content

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%

answer

  1. calling convention vs symbol name
  2. rustc mangles names by default
  3. an attribute with a safety promise
  4. C-compatible layout for structs

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.

solid answer

~50 s

Two separate things make a Rust function callable from C. `extern "C"` sets the **ABI**, so arguments and the return value travel the way a C compiler expects. `#[unsafe(no_mangle)]` stops rustc from **mangling** the symbol, so the object file exports plain `kz_stats_ratio` and a C prototype with that name links to it. Since the 2024 edition `no_mangle` is an unsafe attribute: the bare `#[no_mangle]` fails with `error: unsafe attribute used without unsafe`, because a symbol name is global and a clash (say, exporting `malloc`) breaks the program with no unsafe code in sight. Types crossing the boundary must have a C layout: a plain struct triggers the `improper_ctypes_definitions` warning, and `#[repr(C)]` fixes it. A function that dereferences a raw pointer argument should itself be `pub unsafe extern "C" fn`, so safe Rust callers cannot pass it garbage.

code

rust · 20 lines
rust
use std::ffi::c_int;

#[repr(C)]
pub struct KzStats {
    pub bytes_in: u64,
    pub bytes_out: u64,
    pub level: c_int,
}

/// # Safety
/// `stats` must be null or point to a live, initialised `KzStats`.
// SAFETY (attribute): no other symbol in the final link is named `kz_stats_ratio`.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn kz_stats_ratio(stats: *const KzStats) -> f64 {
    // SAFETY: guaranteed by this function's contract above.
    match unsafe { stats.as_ref() } {
        Some(s) if s.bytes_in > 0 => s.bytes_out as f64 / s.bytes_in as f64,
        _ => 0.0,
    }
}

go deeper

for a junior

Recall the pair: extern "C" for the calling convention, #[unsafe(no_mangle)] for the plain symbol name. Mention #[repr(C)] for any struct that crosses.

for a middle

Explain mangling and why C cannot find a mangled name, and why edition 2024 makes no_mangle an unsafe attribute. Quote the improper_ctypes_definitions warning and its repr(C) fix.

for a senior

Point out that a safe extern "C" fn dereferencing a raw pointer is unsound for Rust callers, and make such exports unsafe with a Safety section. Keep panics from leaving the function and prefix symbols to avoid clashes.

for a principal

Treat the exported surface as a stable C API: a header that is generated or checked in CI, prefixed names, only repr(C) or opaque types, and a policy for adding functions without breaking hosts.

## Two jobs, two pieces of syntax To let a C host call a Rust function by name, two separate problems must be solved: 1. **How the call travels.** The caller and callee must agree on the **ABI** (application binary interface): which registers or stack slots hold each argument, how a struct is returned, who cleans up. Rust's own ABI is unspecified and can change between releases. `extern "C"` on a function definition switches that one function to the target's C calling convention. 2. **How the linker finds it.** rustc normally **mangles** symbol names, encoding the crate, the module path and a hash into the symbol so that two `fn new` in different crates never collide. A C program declares `double kz_stats_ratio(const KzStats *);` and asks the linker for exactly `kz_stats_ratio`. `#[unsafe(no_mangle)]` tells rustc to emit the plain name. Neither implies the other. An `extern "C" fn` without the attribute has the right calling convention and a mangled name, so the C link fails with an undefined symbol. A `no_mangle` function with the Rust ABI is found by the linker, but C then calls it under a convention nobody guarantees matches. ## Why the attribute is unsafe since the 2024 edition All the symbols in a final link share **one global namespace**. Mangling normally keeps names unique, and `no_mangle` gives that protection up. The 2024 edition guide shows a program with only safe code that crashes on most Unix-like platforms because a function was exported as `malloc`. So Rust 1.82 let you write `#[unsafe(no_mangle)]` in every edition, and the 2024 edition made it mandatory for `no_mangle`, `export_name` and `link_section`. On edition 2024, rustc 1.99 rejects the old spelling: ```plaintext error: unsafe attribute used without unsafe --> e2bad.rs:1:3 | 1 | #[no_mangle] | ^^^^^^^^^ usage of unsafe attribute ``` The promise you make is narrow: no other symbol in the link has this name. By convention a `// SAFETY:` comment above the attribute says so. ## Layout of what crosses The function's types must mean the same thing on both sides: | Rust type | Crosses as | Note | |---|---|---| | `u64`, `f64`, `c_int` | the matching C scalar | use `std::ffi` aliases for C's `int`, `long`, `char` | | `*const T`, `*mut T` | `const T *`, `T *` | null is allowed; Rust must check it | | `#[repr(C)] struct` | a C struct with the same field order | the layout lesson covers padding rules | | plain `struct` | not FFI-safe | field order and padding are unspecified | | `String`, `Vec<T>`, `&str` | not FFI-safe | pass pointer plus length, or a `CString` pointer | For an exported function returning a plain struct, rustc 1.99 warns ``extern` fn uses type `Stats`, which is not FFI-safe`` under the lint `improper_ctypes_definitions`, and suggests `#[repr(C)]` or `#[repr(transparent)]`. That is a warning, not an error, and treating it as an error in CI is a good idea. ## Safe or unsafe on the Rust side `extern "C"` says nothing about safety. An `extern "C" fn` defined in Rust is safe to call from Rust unless it is also marked `unsafe`. That matters when the function takes a raw pointer and dereferences it: - `pub extern "C" fn kz_stats_ratio(stats: *const KzStats)` that reads `*stats` is **unsound**: safe Rust could call it with a dangling pointer. Clippy's `not_unsafe_ptr_arg_deref` lint, deny by default, rejects this shape, reporting that the public function might dereference a raw pointer but is not marked unsafe. - `pub unsafe extern "C" fn kz_stats_ratio(...)` with a `# Safety` doc section puts the obligation on callers. C callers do not see the difference, and Rust callers must write `unsafe`. - Inside it, the 2024 edition warns through `unsafe_op_in_unsafe_fn` unless each unsafe operation sits in its own `unsafe { }` block. That keeps the dangerous lines visible. ## Producing something C can link The crate is built as a `staticlib` or `cdylib`; choosing the crate type is a Cargo manifest setting. The C side needs a header with matching prototypes and struct definitions. You can write it by hand for a handful of functions or generate it with cbindgen. Then: 1. Mark each export `extern "C"` and `#[unsafe(no_mangle)]`, with a unique, prefixed name such as `kz_`. 2. Give every struct that crosses `#[repr(C)]`. Hand over anything else only behind a pointer. 3. Make pointer-taking exports `unsafe extern "C" fn`, and check for null before turning a pointer into a reference with `as_ref`. 4. Keep panics from escaping. An `extern "C"` function that panics aborts the process, which the lesson on callbacks and unwinding covers.

  • Why can a Rust `extern "C" fn` that dereferences its pointer argument be unsound even though C callers are fine?
    Without `unsafe` on the definition, safe Rust code can call it too, passing a dangling or misaligned pointer, and the dereference is then undefined behaviour reached from safe code. Declaring it `pub unsafe extern "C" fn` with a `# Safety` section moves the obligation to callers. C sees the same symbol either way.
  • What can go wrong when two linked libraries export the same unmangled name?
    Depending on the platform and how the libraries are linked, the linker reports a duplicate symbol or one definition silently wins, so calls meant for one library reach the other. Prefix exports with a library tag such as `kz_`, and treat the `unsafe(no_mangle)` comment as the place where that uniqueness is promised.

  • extern "C" on a function also stops rustc from mangling its name.
  • #[no_mangle] alone is enough; edition 2024 accepts it unchanged.
  • Any struct of plain integers already has C layout.
  • An extern "C" fn defined in Rust is unsafe to call from Rust.
  • The improper_ctypes_definitions warning is harmless to ignore.

Assumes Rust 1.99 on edition 2024; #[unsafe(no_mangle)] became available in Rust 1.82 and mandatory with the 2024 edition (Rust 1.85).