expression

Nullable synchronous C callback

A nullable C function pointer can be represented as Option of a C ABI function pointer. This local synchronous example invokes a callback before returning and never stores it. A real asynchronous registration needs lifetime, thread and unregister contracts. Expected stdout (not executed): 1 -1 Common mistake: Calling a null callback or assuming a captured Rust closure is a C function pointer.

Formal Syntax & Structure

rust syntaxrust
Option<extern "C" fn(c_int) -> c_int>

Working Example

Example Snippetrust
#![deny(unsafe_op_in_unsafe_fn)]fn main() {    use std::ffi::c_int;    extern "C" fn positive(n: c_int) -> c_int { if n > 0 { 1 } else { 0 } }    fn call(cb: Option<extern "C" fn(c_int) -> c_int>, n: c_int) -> c_int {        match cb { Some(f) => f(n), None => -1 }    }    println!("{} {}", call(Some(positive), 3), call(None, 3));}
Rust Reference