liveBook · Manning

Trampoline

As explained in Embedded Software with Rust

A small intermediary function that adapts a generic callback interface to the specific function and data types expected by the implementation.

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

How Embedded Software with Rust covers it

How deep it goes
Shows pointer recovery in a complete event-counter example and notes the hardware requirement of its atomic operation.
Examples
Demonstrates counting callback invocations with a static atomic counter passed through the context pointer.
What it assumes
Assumes a C callback interface that passes a context pointer back when invoking the callback.
What you can do after
Apply the pattern by registering a Rust callback and context pointer, then recovering the expected type inside the callback.
How it connects
Connects C callbacks, opaque pointers, Rust FFI, and atomic counters.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Embedded Software with Rust. The section links point to the parts of the book it draws on.