expression

Synchronous callback with a context pointer

A context pointer lets a callback access caller-owned state. The callback contract requires a live, aligned, uniquely accessible u32, and forbids retaining the pointer. The callback cannot panic here because it only assigns a value. This direct call models a synchronous foreign callback. Expected stdout (not executed): 42 Common mistake: Passing a pointer to temporary state when a library retains it after returning.

Formal Syntax & Structure

rust syntaxrust
unsafe extern "C" fn(*mut c_void, u32)

Working Example

Example Snippetrust
#![deny(unsafe_op_in_unsafe_fn)]fn main() {    use std::ffi::c_void;    unsafe extern "C" fn receive(ctx: *mut c_void, value: u32) {        // SAFETY: caller provides a live exclusive u32 for this call.        unsafe { *ctx.cast::<u32>() = value; }    }    let mut last = 0_u32;    let ctx = (&mut last as *mut u32).cast::<c_void>();    // SAFETY: last is live and exclusively accessible; no pointer is retained.    unsafe { receive(ctx, 42); }    println!("{last}");}
Rust Reference