Answer#
The pattern has three layers. The bottom is the raw declaration, which Rust cannot check. The middle is a safe function that makes sure the conditions the C function needs are true. The top is ordinary Rust code that never sees a pointer.
The example calls qsort from the C runtime, which every Rust program on the Windows target already links, so no C file is needed to run it. qsort is a good test because it takes a pointer, a count, an element size and a callback. It was compiled and run with rustc 1.93.0.
use std::cmp::Ordering;
use std::ffi::c_void;
extern "C" {
// from the C runtime that every Rust program on this target already links
fn qsort(base: *mut c_void, n: usize, size: usize, cmp: extern "C" fn(*const c_void, *const c_void) -> i32);
}
extern "C" fn cmp_i32(a: *const c_void, b: *const c_void) -> i32 {
// SAFETY: qsort passes pointers to two elements of the array, which we declared as i32.
let (a, b) = unsafe { (*(a as *const i32), *(b as *const i32)) };
match a.cmp(&b) {
Ordering::Less => -1,
Ordering::Equal => 0,
Ordering::Greater => 1,
}
}
/// The safe wrapper: callers never see a pointer.
fn c_sort(v: &mut [i32]) {
// SAFETY: the pointer and the length come from one valid slice, and the element size is size_of::<i32>().
unsafe { qsort(v.as_mut_ptr().cast(), v.len(), std::mem::size_of::<i32>(), cmp_i32) }
}
fn main() {
let mut v = [5, -2, 9, 0, 3];
c_sort(&mut v);
println!("{v:?}");
let mut e: [i32; 0] = [];
c_sort(&mut e);
println!("{e:?}");
}[-2, 0, 3, 5, 9]
[]Why the wrapper is the important part: c_sort accepts only a &mut [i32], so the pointer, the count and the element size always agree. Every unsafe block carries a SAFETY: comment that states why the call is allowed. A reviewer reads those comments instead of the whole program. (In real code you would use v.sort(). qsort is only the demonstration of the mechanism.)
How to do it#
- Declare the functions you need in an
extern "C"block, with types that match the C header:c_int,c_char,*const T,*mut T,usizeforsize_t. A wrong declaration is undefined behaviour that no tool will catch, which is why generating them is better. - Generate the declarations with
bindgenfrom the C header, inbuild.rsor on the command line, for anything larger than a handful of functions.bindgenneeds libclang. It was not run for this thread. - Compile your own C files by adding the
cccrate as a build dependency and callingcc::Build::new().file("src/legacy.c").compile("legacy")inbuild.rs. Cargo then links the result. It needs a C compiler on the build machine, and none is installed on the machine used for this thread, so this step is described from the crate documentation and was not run here. - Link a prebuilt library with
println!("cargo:rustc-link-lib=name")inbuild.rs, or#[link(name = "name")]on theexternblock. - Wrap each function (or group) in a safe function like
c_sort. Check for null, check lengths, convert strings (see the thread on C strings), and turn error codes intoResult(see the thread on error codes). - Put the wrapper in its own module so that all
unsafeis in one place.
Common mistakes#
- Letting a Rust panic unwind through a C frame. Catch panics at the boundary (
std::panic::catch_unwind) or avoid panicking in callbacks. - Passing a pointer that C keeps after the call, to a value Rust then moves or frees. If C stores it, the memory must stay in place and alive; a
Boxleaked on purpose, with a matching free function, is the usual approach. - Declaring a function with the wrong argument types because it "looks the same". Let
bindgenread the header. - Forgetting that C code can corrupt memory. Safe Rust around it does not make the C code safe.
Related questions#
Does extern "C" need unsafe in the 2024 edition?#
In the 2024 edition the block is written unsafe extern "C" { ... }. The example above uses the 2021 edition spelling. Check the edition in your Cargo.toml and the compiler message if it complains.
How do I call Rust from C instead?#
Write #[no_mangle] pub extern "C" fn functions (see the thread on Rust and Python with ctypes, which exposes such functions), build the crate as cdylib or staticlib, and write the C header by hand or generate it with cbindgen.
Sources#
- The Rustonomicon, "Foreign Function Interface": https://doc.rust-lang.org/nomicon/ffi.html
- bindgen user guide: https://rust-lang.github.io/rust-bindgen/
- The
cccrate: https://docs.rs/cc