A context pointer carries caller-provided state alongside a callback function pointer. The C library stores it without inspecting it and passes it back unchanged whenever it invokes the callback. section 8.4.3
In Rust, a trampoline receives the generic `void *`, converts it to the expected type, and passes it to the callback logic. The pointer must remain valid while callbacks may fire; state retained by C needs a `'static` lifetime. section 8.4.3 section 8.7
use core::ffi::{c_int, c_void};
use core::sync::atomic::{AtomicU32, Ordering};
unsafe extern "C" {
fn register_callback_ctx(
cb: unsafe extern "C" fn(c_int, *mut c_void),
ctx: *mut c_void,
);
}
static EVENT_COUNT: AtomicU32 = AtomicU32::new(0);
// SAFETY:`ctx` must be exactly the pointer registered below: a valid,
// live `*const AtomicU32` for as long as the callback might fire.
unsafe extern "C" fn count_events(_value: c_int, ctx: *mut c_void) {
// SAFETY: `ctx` is the pointer we registered below, and the
// static it points to lives for the life of the program.
let counter = unsafe { &*(ctx as *const AtomicU32) };
counter.fetch_add(1, Ordering::Relaxed);
}
pub fn install() {
unsafe {
register_callback_ctx(
count_events,
&EVENT_COUNT as *const _ as *mut c_void,
);
}
}
This example registers a callback with a pointer to a static atomic counter, then increments it whenever the callback fires. section 8.4.3
