A trampoline adapts a C callback’s generic `void *` context pointer to the specific Rust type the callback needs. It recovers that type, then hands control to the code that does the actual work. section 8.4.3
Counting callback events
Register a callback with a pointer to a static `AtomicU32`. The trampoline casts the returned context pointer back to `AtomicU32` and increments it. This example’s `fetch_add` requires compare-and-swap support, available on Cortex-M3 and above but not Cortex-M0/M0+. section 8.4.3
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,
);
}
}
See the complete Rust callback registration and trampoline implementation. section 8.4.3
