Sub topic 10
Calling C functions with extern blocks
This chapter assumes you know ownership and borrowing, raw pointers, and the rule that unsafe marks code whose safety the programmer must justify. You should also be able to build and run a Cargo project. The chapter covers how Rust declares and calls functions written in C, what the compiler checks, and what it leaves to you.
Why foreign calls are unsafe
Rust verifies a function call by looking at its signature and body. For a function written in C, the compiler sees neither the body nor the real contract. The C compiler produced machine code with no ownership, lifetime, or nullability information. If you declare a function with the wrong signature, Rust cannot detect it. The linker only matches symbol names.
For this reason, foreign functions are unsafe to call by default. The declaration is a claim you make about the C side, and the compiler trusts it.
Declaring foreign functions
You declare foreign functions inside an unsafe extern block. The string after extern names the ABI, which is the calling convention that defines how arguments and return values are passed. "C" is the platform's C ABI.
unsafe extern "C" {
fn abs(input: i32) -> i32;
}
fn main() {
// SAFETY: C's `abs` has no preconditions beyond a valid i32 argument.
let v = unsafe { abs(-3) };
println!("{v}");
}The unsafe before extern says that the declarations in the block are assertions the programmer vouches for. In the 2024 edition a plain extern "C" { ... } block is an error. Earlier editions accept the unsafe extern form from Rust 1.82 onward, so you can use it everywhere.
The C standard library is already linked into most Rust programs, so abs resolves without extra setup. For other libraries, add a #[link(name = "m")] attribute to the block, or use a build script. Both tell the linker which library to search.
Matching C types
Your Rust signature must have the same size, alignment, and ABI as the C one. Use the C-compatible aliases in std::ffi instead of guessing at integer widths.
| C type | Rust type |
|---|---|
| `int` | `std::ffi::c_int` (usually `i32`) |
| `long` | `std::ffi::c_long` (32 or 64 bits depending on platform) |
| `char` | `std::ffi::c_char` |
| `size_t` | `usize` (on mainstream platforms) |
| `double` | `f64` |
| `void *` | `*mut std::ffi::c_void` |
| `const char *` | `*const std::ffi::c_char` |
long is the classic trap. It is 64 bits on 64-bit Linux and 32 bits on 64-bit Windows. Writing i64 for a C long works on one platform and corrupts data on the other. c_long gives the correct width on each platform.
Passing strings
Rust &str values are not null-terminated and may contain interior zero bytes. C strings are null-terminated. CString bridges the two. It checks that there are no interior zero bytes and appends the terminator.
use std::ffi::{CString, c_char};
unsafe extern "C" {
fn strlen(s: *const c_char) -> usize;
}
fn c_strlen(text: &str) -> Option<usize> {
// Fails if `text` contains an interior zero byte.
let c_text = CString::new(text).ok()?;
// SAFETY: `c_text` is a valid null-terminated string and stays alive
// until after the call returns.
Some(unsafe { strlen(c_text.as_ptr()) })
}
fn main() {
println!("{:?}", c_strlen("hello"));
println!("{:?}", c_strlen("bad\0text"));
}The program prints Some(5) and then None.
A common bug is a dangling pointer from a temporary:
use std::ffi::{CString, c_char};
fn main() {
let ptr: *const c_char = CString::new("hi").unwrap().as_ptr();
// The temporary CString is dropped at the end of the statement above.
// `ptr` now dangles. Passing it to C is undefined behavior.
let _ = ptr;
}Bind the CString to a variable that outlives every use of the pointer, as c_text does in c_strlen.
For the reverse direction, std::ffi::CStr::from_ptr wraps a *const c_char returned by C. It is itself unsafe, because the pointer must be non-null, null-terminated, and valid for the lifetime you choose. The CStr borrows the C memory. It does not copy or free it.
Marking individual items safe
Sometimes a foreign function really has no preconditions. Inside an unsafe extern block you can mark such an item safe, so callers need no unsafe block. Mark the others unsafe explicitly. This is available from Rust 1.82.
use std::ffi::c_char;
unsafe extern "C" {
pub safe fn abs(input: i32) -> i32;
pub unsafe fn strlen(s: *const c_char) -> usize;
}
fn main() {
// `abs` is declared `safe`, so no unsafe block is needed.
println!("{}", abs(-9));
let bytes = b"rust\0";
// SAFETY: `bytes` is a null-terminated array that outlives the call.
let n = unsafe { strlen(bytes.as_ptr().cast()) };
println!("{n}");
}Writing safe is a promise that no argument values or program state can make the call cause undefined behavior. Treat it like writing a safe wrapper. If you are unsure, leave the item as the default unsafe.
Passing Rust callbacks to C
C APIs often take function pointers. A Rust function can be passed as one if it uses the C ABI. The C standard library's qsort is a good example:
use std::ffi::c_void;
unsafe extern "C" {
fn qsort(
base: *mut c_void,
count: usize,
size: usize,
compare: extern "C" fn(*const c_void, *const c_void) -> i32,
);
}
extern "C" fn compare_i32(a: *const c_void, b: *const c_void) -> i32 {
// SAFETY: qsort calls us with pointers to elements of the i32 array
// that we passed in, so both are valid and aligned for i32.
let (a, b) = unsafe { (*a.cast::<i32>(), *b.cast::<i32>()) };
a.cmp(&b) as i32
}
fn main() {
let mut values = [5, 2, 9, 1, 7];
// SAFETY: `values` is a valid array of `len` i32 elements, and
// `compare_i32` matches the element type.
unsafe {
qsort(
values.as_mut_ptr().cast(),
values.len(),
std::mem::size_of::<i32>(),
compare_i32,
);
}
println!("{values:?}");
}The output is [1, 2, 5, 7, 9]. The safety comments point to the two facts that matter. The element size and count must describe the real buffer, and the callback must interpret the pointers as the type that was actually sorted.
A panic that unwinds out of an extern "C" function aborts the process in current Rust, so a callback cannot propagate a panic to C. If your callback can panic, catch it with std::panic::catch_unwind and convert it to an error code.
Structs and layout
To pass a struct by pointer or by value, mark it #[repr(C)]. Without it, Rust may reorder fields and the layout will not match the C definition.
#[repr(C)]
struct Point {
x: f64,
y: f64,
}
fn main() {
println!("{}", std::mem::size_of::<Point>());
}Only use types with a defined C representation in foreign signatures. String, Vec<T>, &str, trait objects, and Option<Box<T>>-style Rust-specific types have no C equivalent. References are acceptable only when C promises a non-null, aligned pointer. Raw pointers are the safer default at the boundary.
bool is a special case. Rust requires a bool to be exactly 0 or 1. If a C function returns an arbitrary integer, declare it as an integer type, then compare it yourself. Otherwise any other value is a validity violation.
Exporting Rust functions to C
The reverse direction also uses the C ABI. Give the function extern "C" and a stable symbol name:
#[unsafe(no_mangle)]
pub extern "C" fn rust_add(a: i32, b: i32) -> i32 {
a + b
}no_mangle stops the compiler from changing the symbol name. The attribute is written #[unsafe(no_mangle)] because a name collision with another symbol can cause undefined behavior. A C program can call this function only if you build the crate as a staticlib or cdylib in Cargo.toml.
What a foreign call involves
Common failure modes
- Wrong signature. Declaring
fn abs(x: i64) -> i64for a C function that takesintcompiles and links. It then reads garbage from registers or the stack. Check the C header, or generate bindings withbindgen. - Null pointers. C functions often return null for failure. Check for null with
ptr.is_null()before you dereference or build a reference. - Ownership mismatch. Memory allocated by C must be freed by C, using the library's free function. Memory from Rust's allocator must be freed by Rust. Mixing them is undefined behavior.
- Threading. If a C library keeps global state and is not thread-safe, calling it from several Rust threads causes data races that Rust cannot detect.
- Lifetimes. A pointer you hand to C may be stored by C and used after your function returns. The Rust borrow checker cannot see that. Keep the data alive for as long as C may use it.
Exercises
Exercise
The following declaration compiles and links, but crashes on 64-bit Windows while working on 64-bit Linux. What is the likely problem, and how do you fix it? unsafe extern "C" { fn labs(x: i64) -> i64; }
Show answer
The C function labs takes and returns long, which is 64 bits on 64-bit Linux but 32 bits on 64-bit Windows. The i64 signature only matches on Linux. Declare it with std::ffi::c_long so the width follows the platform's C definition.
Exercise
Why is let p = CString::new("hi").unwrap().as_ptr(); followed by passing p to a C function undefined behavior, and how do you write it correctly?
Show answer
The CString is a temporary that is dropped at the end of the statement, so p points to freed memory. Bind it first with let c = CString::new("hi").unwrap();, then use c.as_ptr() in a call that finishes while c is still in scope.