Skip to content
Tutorials Center
My learning

Topics

Lesson 73 of 132 ยท Smart Pointers and Memory

FFI: Calling C and Being Called

Call C functions from Rust and expose Rust functions to C. Learn unsafe extern blocks, repr(C), CString and CStr, callbacks, no_mangle in 2024, bindgen and cbindgen.

Rust does not live alone. Operating systems expose C interfaces, databases ship C libraries, and decades of useful code (image decoders, cryptography, compression) is written in C. The Foreign Function Interface (FFI) is how Rust calls into that world, and how other languages call into Rust. Done well, it is a small, tidy boundary; done carelessly, it is where most memory-safety bugs in Rust programs come from.

This lesson shows both directions: declaring and calling C functions from Rust, passing strings and structs across the boundary, handing Rust functions to C as callbacks, and exporting Rust functions with a stable name. Every example runs against the C standard library that Rust programs already link, so you can try all of it in the browser. It builds on Unsafe Rust and Memory Layout and Sizes.

FFI needs unsafe, because the compiler cannot see inside C code. Everything it checks stops at the boundary: you promise that the declared signature matches the real function and that you obey its rules about null, lengths and ownership.

Calling a C function

C functions are declared in an extern block. In the 2024 edition the block must be written unsafe extern, which makes it explicit that the declarations are promises you are making. The ABI string "C" tells Rust to use the C calling convention.

Rust Calling abs, labs and toupper from the C library

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

The types c_int, c_long, c_char, c_void and friends live in std::ffi (and core::ffi). Use them instead of guessing i32: a C long is 64 bits on Linux but 32 bits on 64-bit Windows, and the aliases pick the right one for the platform.

Safe items in an extern block

If a foreign function has no preconditions at all (any argument is fine, nothing can go wrong), you can mark it safe inside the block. Callers then need no unsafe. This keyword (stable since Rust 1.82) is only valid inside unsafe extern, and you are making the promise that it really is safe.

Rust Marking a foreign function safe

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Use safe fn sparingly. If any input could cause UB (a pointer, a length, a handle), keep the function unsafe and wrap it yourself.

Strings: CString and CStr

Rust strings are UTF-8 with an explicit length and may contain a zero byte. C strings are a pointer to bytes ending in a zero byte ('\0'), with no length. Passing one to the other needs care, and the standard library has two types for it:

  • CString owns a C-style string. Building it from Rust data adds the trailing zero and refuses data with an interior zero (CString::new returns a Result).
  • CStr borrows one: a view of a zero-terminated byte sequence, like &str is to String.

C-string literals (c"hello", stable since Rust 1.77) make a &'static CStr at compile time, with the terminator included.

Rust Passing strings to strlen

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Note the result for hรฉllo: strlen counts bytes, and รฉ takes two bytes in UTF-8, so the length is 6, not 5. That is a general FFI lesson: C measures bytes, and Rust's .len() on a str does too, but .chars().count() does not.

A common bug is passing a pointer to a temporary:

Rust
// WRONG: the CString is dropped at the end of the statement,
// so `ptr` dangles by the time anyone uses it.
let ptr = CString::new("hello").unwrap().as_ptr();

Keep the CString in a variable that lives as long as the pointer is used.

Receiving a C string

When C hands you a *const c_char, wrap it in CStr::from_ptr (unsafe: the pointer must be valid and zero-terminated) and then decide how to convert it. to_str() checks for valid UTF-8; to_string_lossy() replaces invalid bytes and returns a Cow<str> (see Cow).

Rust Reading a string returned by C

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

The pattern is always the same: check for null, wrap, copy into an owned Rust value (.into_owned()) before the C side can free or overwrite its buffer. In real programs you would use std::env::var instead of getenv; the point here is the boundary.

Structs: repr(C)

Rust's default struct layout is unspecified (it may reorder fields; see Memory Layout), so a struct passed to C must be #[repr(C)], whose layout matches what a C compiler would produce. The C function div takes two integers and returns a struct div_t { int quot; int rem; } by value:

Rust Returning a repr(C) struct from C

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Only types with a defined C representation should cross the boundary: integers and floats, raw pointers, Option<&T> and Option<extern "C" fn(...)> (where None becomes a null pointer, thanks to niche optimization), #[repr(C)] structs and enums with #[repr(i32)]-style integer types. Never pass String, Vec, &str, trait objects or plain Rust enums with data. If you need to pass a buffer, pass a pointer and a length.

Callbacks: passing Rust functions to C

Many C APIs take a function pointer. In Rust, such a function must be declared extern "C" so its calling convention matches. The classic example is qsort, which sorts raw memory using a comparison callback.

Rust qsort with a Rust callback

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

sort_descending is the safe wrapper: its signature uses a slice, which makes the pointer and length always consistent, and the unsafe call is hidden inside. That is the shape of every good FFI binding: a thin -sys-style layer of raw declarations, and a safe layer on top that enforces the C library's rules.

A panic must not unwind through C code. Since Rust 1.81, a panic that tries to escape an extern "C" function aborts the process. If a callback can fail, catch the panic with std::panic::catch_unwind or return an error code.

C callbacks usually carry a void *user_data pointer so you can pass state. In Rust you pass a pointer to your state as *mut c_void and cast it back inside the callback; the state must outlive the C call.

Being called: exporting Rust functions

To make a Rust function callable from C (or from Python, Node.js, Go and others, which all speak the C ABI), declare it extern "C". To give it a predictable symbol name, add #[unsafe(no_mangle)].

Normally Rust mangles names (adds module and hash information) so add could be defined twice in different crates. A C linker looks for the plain name. Turning mangling off is unsafe, because a duplicate symbol name can silently replace another function, so since the 2024 edition the attribute is written #[unsafe(no_mangle)] (before 2024: #[no_mangle]). The same applies to #[unsafe(export_name = "...")].

Rust
// lib.rs of a crate built as a C-compatible library
#[unsafe(no_mangle)]
pub extern "C" fn rust_add(a: i32, b: i32) -> i32 {
    a + b
}

And in Cargo.toml:

TOML
# Read-only: needs a Cargo project
[lib]
crate-type = ["cdylib"]   # a shared library (.so / .dll / .dylib); use "staticlib" for a .a/.lib

A C program would then declare int rust_add(int a, int b); and link against the library. The function can also be called from Rust like any other; in a single file we can exercise the exact signature C would see, including a small "handle" API that C-style code uses to manage Rust objects it cannot see inside:

Rust An exported API with an opaque handle

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

This is the opaque pointer pattern: C holds a Counter* it cannot look inside, and calls functions to create, use and destroy it. Box::into_raw gives up Rust's ownership and returns a raw pointer; Box::from_raw takes it back so Drop runs. Forgetting counter_free leaks the memory; calling it twice is a double free. Documenting who owns what is the heart of FFI design.

Generating bindings

Writing declarations for a big C library by hand is tedious and error-prone. Two tools automate it, and both are normally run from a Cargo project, so the snippets below are read-only:

  • bindgen reads C headers and generates Rust declarations: #[repr(C)] structs, extern functions, constants. Run it from a build.rs script. Crates ending in -sys (such as libsqlite3-sys) are generated bindings; a safe crate on top wraps them.
  • cbindgen goes the other way: it reads your Rust extern "C" API and writes a C header, so your C users do not have to guess signatures.
Terminal
# Read-only: run on your own machine
cargo install bindgen-cli cbindgen
bindgen wrapper.h -o src/bindings.rs
cbindgen --lang c --output my_library.h

For C++ libraries, the cxx crate provides a safer bridge than raw extern "C", and PyO3 and napi-rs cover Python and Node.js. They all build on the ideas in this lesson.

Rules that prevent most FFI bugs

  1. Match signatures exactly. A wrong type or argument count is undefined behavior the compiler cannot catch.
  2. Use c_* types and #[repr(C)] for everything that crosses.
  3. Document ownership. Who allocates, who frees, and with which allocator? Memory from Rust's Box must be freed by Rust, memory from malloc by free.
  4. Check pointers for null before dereferencing, and lengths before slicing.
  5. Never unwind across the boundary. Catch panics or abort.
  6. Wrap the raw layer in a safe API and keep the unsafe in one small module.
  7. Test with Miri where possible (it cannot run foreign code) and with sanitizers for the full program.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. In the 2024 edition, how must a block of foreign function declarations be written?

    The 2024 edition requires unsafe extern, making it explicit that the declarations are unchecked promises. Inside, you can mark individual items safe fn when they have no preconditions.
  2. 2. Why use CString::new instead of passing s.as_ptr() of a Rust String to C?

    C expects a zero-terminated string. A Rust String has no terminator, so C would read past its end. CString::new appends the zero and returns an error if the data already contains one.
  3. 3. What is the bug in let p = CString::new("hi").unwrap().as_ptr(); followed by using p?

    The CString lives only until the end of the statement. The pointer then dangles; bind the CString to a variable that outlives the pointer's use.
  4. 4. Why must a struct passed to a C function be #[repr(C)]?

    repr(C) fixes field order and padding to the C rules, so both sides agree on where each field is.
  5. 5. What does #[unsafe(no_mangle)] do in the 2024 edition?

    no_mangle can cause symbol clashes, so 2024 requires the unsafe(...) wrapper to mark that you take responsibility.

Summary

  • Declare foreign functions in unsafe extern "C" { ... }; calls need unsafe unless an item is marked safe fn.
  • Use std::ffi types (c_int, c_char, c_void) and #[repr(C)] structs; never pass String, Vec or &str directly.
  • CString owns a zero-terminated string, CStr borrows one, and c"..." literals build &CStr at compile time. Keep a CString alive while C uses its pointer.
  • Callbacks are extern "C" fn items; panics must not unwind across the boundary.
  • Export functions with extern "C" and #[unsafe(no_mangle)], build with crate-type = ["cdylib"] or "staticlib", and manage ownership with opaque pointers (Box::into_raw and Box::from_raw).
  • bindgen generates Rust declarations from C headers; cbindgen generates C headers from Rust.
  • Wrap raw bindings in a safe API and document who owns what.

Next: Threads