liveBook · Manning

Context pointer

As explained in Embedded Software with Rust

A generic pointer passed alongside a callback function pointer so a library can return associated caller-provided data when invoking the callback.

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

How Embedded Software with Rust covers it

How deep it goes
Explains opaque storage, callback return, Rust trampoline conversion, and the lifetime requirement for retained pointers.
Examples
Uses a sensor running-average struct and a static `AtomicU32` callback counter.
What you can do after
Build it from scratch by registering a callback with a valid state pointer and recovering that state in Rust.
How it connects
Connects callbacks to the C ABI, raw pointers, Rust trampolines, and static state.

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.