Sub topic 11
Passing callbacks and user data to C
Many C libraries call back into your code. A sort function asks you to compare two items. An iterator hands you each element. An event library tells you when something happens. This chapter shows how to give C a Rust function to call, how to give that function access to Rust state, and what can go wrong.
It assumes you have read the earlier chapters on extern blocks, C types in std::ffi, and safe wrappers. It also assumes you know Rust closures and generics at a basic level.
What C means by a callback
A C callback is a function pointer. C code receives the address of a function and calls it later. In C you write the type like this:
void for_each_item(void (*cb)(int, void *), void *user_data);The callback cb takes an int and a void *. Because C has no closures, a callback cannot capture variables. The usual workaround is the user_data argument, an opaque void * that the library stores and passes back to the callback unchanged. The library never looks inside it. Your callback casts it back to a real type and uses it.
In Rust, a pointer to a C-callable function has the type extern "C" fn(...). The extern "C" part makes the function use the C calling convention, so C and Rust agree on where arguments and the return value go.
A callback without user data: qsort
The C standard library function qsort takes a comparison callback and no user data. That makes it a good first example, and it runs without a build script.
use std::ffi::{c_int, c_void};
unsafe extern "C" {
fn qsort(
base: *mut c_void,
nmemb: usize,
size: usize,
compar: extern "C" fn(*const c_void, *const c_void) -> c_int,
);
}
extern "C" fn compare(a: *const c_void, b: *const c_void) -> c_int {
let (a, b) = unsafe { (*(a as *const i32), *(b as *const i32)) };
a.cmp(&b) as c_int
}
fn main() {
let mut values = [5, 2, 9, 1];
unsafe {
qsort(
values.as_mut_ptr() as *mut c_void,
values.len(),
size_of::<i32>(),
compare,
);
}
println!("{values:?}");
}The program prints [1, 2, 5, 9].
Three points matter here:
compareis declared withextern "C". A plain Rustfnhas an unspecified calling convention, and the compiler rejects it where anextern "C" fnpointer is expected.- The callback receives
*const c_void, so it must cast to the real element type. The cast is only correct because we passedi32elements andsize_of::<i32>(). The compiler cannot check this. Orderingis a fieldless enum with the values -1, 0 and 1, soas c_intgives the negative, zero or positive result thatqsortexpects.
A free function can only reach global state. For anything else you need user data.
Passing state through user data
Take the hypothetical C API from the spine:
void for_each_item(void (*cb)(int, void *), void *user_data);Suppose for_each_item calls cb(v, user_data) once for each item. To sum the items, give C a pointer to a local i64 and cast it back in the callback.
use std::ffi::{c_int, c_void};
// Assumed C API: void for_each_item(void (*cb)(int, void *), void *user_data);
unsafe extern "C" {
fn for_each_item(cb: extern "C" fn(c_int, *mut c_void), user_data: *mut c_void);
}
extern "C" fn on_item(value: c_int, user_data: *mut c_void) {
let sum = unsafe { &mut *(user_data as *mut i64) };
*sum += i64::from(value);
}
pub fn total() -> i64 {
let mut sum: i64 = 0;
unsafe { for_each_item(on_item, &mut sum as *mut i64 as *mut c_void) };
sum
}The sequence is:
totalcreatessumon its stack.- It converts
&mut sumto*mut c_voidand hands it to C along withon_item. - C calls
on_itemonce per item and passes the same pointer each time. on_itemcasts the pointer back to*mut i64and updates the sum.
This is sound only if the cast type matches the pointer's real type. If you pass a pointer to an i64 and the callback reads it as an i32, you get undefined behavior and the compiler cannot warn you. Keep the pointer creation and the cast in the same module so you can check that they match.
Using closures with a trampoline
Writing a separate extern "C" function for every use is tedious. A generic trampoline lets callers pass any Rust closure. The trampoline is an extern "C" function that is generic over the closure type. It treats the user data as a pointer to that closure and calls it.
use std::ffi::{c_int, c_void};
// Assumed C API: void for_each_item(void (*cb)(int, void *), void *user_data);
unsafe extern "C" {
fn for_each_item(cb: extern "C" fn(c_int, *mut c_void), user_data: *mut c_void);
}
extern "C" fn trampoline<F: FnMut(c_int)>(value: c_int, user_data: *mut c_void) {
let f = unsafe { &mut *(user_data as *mut F) };
f(value);
}
pub fn for_each<F: FnMut(c_int)>(mut f: F) {
unsafe {
for_each_item(trampoline::<F>, &mut f as *mut F as *mut c_void);
}
}Each distinct closure type F gets its own monomorphized trampoline::<F>. The compiler therefore knows the exact type behind the pointer. The safe function for_each has a signature free of raw pointers, so callers can write:
let mut seen = Vec::new();
for_each(|v| seen.push(v));The closure captures seen mutably, and the trampoline reaches it through the user data pointer. This pattern is how most safe Rust wrappers around callback-based C APIs work.
How long the user data must live
Whether the pointer stays valid depends on when C calls the callback.
| C behavior | Example | Where the state can live |
|---|---|---|
| Calls the callback only before the function returns | `qsort`, `for_each_item` | On the caller's stack, as shown above |
| Stores the callback and calls it later | Event handlers, timers, async completion | On the heap, until C is told to stop |
The first case is simple. The pointer is valid for the whole call because the stack frame outlives it.
The second case is the dangerous one. If you register a pointer to a stack variable and the function returns, C holds a dangling pointer. Move the state to the heap and give C ownership of a raw pointer. You must then take it back exactly once.
use std::ffi::{c_int, c_void};
// Assumed C API:
// int register_handler(void (*cb)(int, void *), void *user_data);
// void unregister_handler(int id); // no callbacks happen after this returns
unsafe extern "C" {
fn register_handler(cb: extern "C" fn(c_int, *mut c_void), user_data: *mut c_void) -> c_int;
fn unregister_handler(id: c_int);
}
extern "C" fn trampoline<F: FnMut(c_int)>(value: c_int, user_data: *mut c_void) {
let f = unsafe { &mut *(user_data as *mut F) };
f(value);
}
pub struct Handler<F: FnMut(c_int)> {
id: c_int,
state: *mut F,
}
impl<F: FnMut(c_int)> Handler<F> {
pub fn new(f: F) -> Handler<F> {
let state = Box::into_raw(Box::new(f));
let id = unsafe { register_handler(trampoline::<F>, state as *mut c_void) };
Handler { id, state }
}
}
impl<F: FnMut(c_int)> Drop for Handler<F> {
fn drop(&mut self) {
unsafe {
unregister_handler(self.id);
drop(Box::from_raw(self.state));
}
}
}Box::into_raw moves the closure to the heap and stops Rust from freeing it. Drop first tells C to stop, then frees the box with Box::from_raw. The order matters: freeing the closure before C stops calling it would leave C calling into freed memory. This is the same RAII pattern as the wrapper chapter, applied to a callback.
If the C library may call the callback from another thread, F also needs to be Send, and you must follow the library's rules about whether callbacks can run concurrently with unregister_handler.
Panics must not cross the boundary
If a Rust callback panics and the panic unwinds into C frames, the result is undefined behavior in older code. Since Rust 1.81, a panic that tries to leave an extern "C" function aborts the process instead. Abort is safer, but your program still dies.
If you would rather report a failure, catch the panic inside the callback and turn it into a status code. The callback below also shows why the return value matters when C's callback type returns int:
use std::ffi::{c_int, c_void};
use std::panic::{catch_unwind, AssertUnwindSafe};
extern "C" fn on_item(value: c_int, user_data: *mut c_void) -> c_int {
let result = catch_unwind(AssertUnwindSafe(|| {
let sum = unsafe { &mut *(user_data as *mut i64) };
*sum += i64::from(value);
}));
if result.is_ok() { 0 } else { -1 }
}The next chapter covers panics in detail. For now, remember that every extern "C" callback is a place where a panic must be handled on purpose.
Common mistakes
- Wrong cast of user data. The type behind
*mut c_voidis not checked. Pass&mut T, cast back toT, and nothing else. - Passing a reference to a reference. If
fis already&mut G, then&mut fis a pointer to the reference, not toG. Cast the same expression in both places. - Dangling state. Stack state is only valid until the function that registered it returns. Use
Box::into_rawfor deferred callbacks. - Double free or leak. Call
Box::from_rawexactly once. If C may never call back, still free the box inDrop. - Aliasing. The callback holds
&mutto the state while your Rust code may also hold it. Do not touch the state from the calling function while C is iterating. - Wrong signature. The compiler cannot compare your
extern "C" fntype with the C header. A wrong argument type compiles and then corrupts data. Generated bindings from bindgen reduce this risk.
Exercise
In the heap-based Handler example, why must unregister_handler run before Box::from_raw drops the closure, and what goes wrong if you swap the two lines?
Show answer
C keeps the user_data pointer and may call trampoline at any time until the handler is unregistered. If the box is freed first, a callback that arrives in between reads freed memory through a dangling pointer, which is undefined behavior (a use-after-free). Unregistering first guarantees, per the C API's contract, that no more callbacks happen, so freeing the closure afterwards is safe.
Exercise
A C function void run(void (*cb)(int, void *), void *ud) calls cb only while run executes. You write pub fn go(mut count: u32) { unsafe { run(trampoline::<fn(c_int)>, &mut count as *mut u32 as *mut c_void) } }, with a trampoline that casts user_data to *mut F. What is wrong?
Show answer
The trampoline is instantiated with F = fn(c_int), so it casts the user data pointer to *mut fn(c_int) and calls it. But the pointer actually refers to a u32. The program reads an integer as a function pointer, which is undefined behavior. The type in the cast must match what was passed: pass a closure of type F and &mut f, or write a callback that casts to *mut u32.