Sub topic 11
Passing callbacks and user data to C
This chapter assumes you can declare C functions in an unsafe extern "C" block, use raw pointers, and write #[repr(C)] structs. It shows how to hand C a Rust function to call back, and how to give that function access to Rust state.
What a callback is in C
Many C APIs take a function pointer. The library calls it later, for example to compare two items or to report each element of a collection. In Rust, the matching type is extern "C" fn(...). The function must use the C calling convention, or C will call it with the wrong register and stack layout.
A runnable example with qsort
The C standard library function qsort sorts an array and calls your comparison function. It is already linked into Rust programs on common platforms.
use std::ffi::{c_int, c_void};
unsafe extern "C" {
fn qsort(
base: *mut c_void,
count: usize,
size: usize,
cmp: 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 details matter here:
compareis a plain function item markedextern "C". Passing its name coerces it to the function pointer type.- C gives the callback
void *, so the callback casts back to the real type. The cast is only correct because the caller passed an array ofi32. Orderingconverts to-1,0, or1, which is the contractqsortexpects.
Passing state with user data
An extern "C" fn cannot capture variables, because a C function pointer has no place to store them. Well-designed C APIs solve this with a void *user_data argument. C passes your pointer back unchanged on every call.
The next example uses a hypothetical C API, void for_each_item(void (*cb)(int, void *), void *user_data);, so it needs a library that provides that function.
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 Rust side erases the type of sum into *mut c_void, and the callback restores it. Nothing checks that the two types agree, so keep the cast and the callback next to each other.
Lifetime rules
The pointer you pass must stay valid for as long as C might use it.
- If C only calls the callback before the function returns, as
for_each_itemdoes, a pointer to a local variable is fine. - If C stores the callback and calls it later, for example a registered event handler, a local variable will dangle. Allocate the state with
Box::into_raw, keep it alive until the library is told to stop, and free it withBox::from_rawafterwards. - If C may call the callback from another thread, the state must be safe to share across threads. Use something like
Mutexor atomics. A bare&mutthrough*mut c_voidgives no such protection.
Panics must not cross the boundary
If a Rust callback panics and the unwind reaches C code, behavior is undefined or the process aborts, depending on the ABI and Rust version. Wrap the callback body in catch_unwind and return a status code instead:
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 }
}This version returns a c_int, so the C declaration must use a callback type that returns int. The callback type in Rust must match the C signature exactly.
Exercise
A C library stores your callback and calls it later from its own event loop. Why is it wrong to pass &mut local_counter as *mut _ as *mut c_void as the user data?
Show answer
The local variable is destroyed when the Rust function returns, but C still holds the pointer and will use it afterwards, which is a dangling pointer. Allocate the state on the heap with Box::into_raw, keep it alive while the library can call back, and free it with Box::from_raw after the callback is unregistered.