Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Callbacks: absl::AnyInvocable and Fn/FnMut/FnOnce

Crubit supports bidirectional function callbacks across C++ and Rust:

Type mappings

DirectionC++ typeRust typeSemantics
C++ $\to$ Rustabsl::AnyInvocable<R(...) const>Box<dyn Fn(...) -> R + Send + Sync>Multiple invocations
C++ $\to$ Rustabsl::AnyInvocable<R(...) &&>Box<dyn FnOnce(...) -> R + Send>Single-use invocation
C++ $\to$ Rustabsl::AnyInvocable<R(...)> (non-const)Box<dyn Fn(...) -> R + Send + Sync>Promoted to Fn
Rust $\to$ C++rs::FnRef<R(...) const>&dyn Fn(...) -> R / impl Fn(...) -> RBorrowed, zero allocation
Rust $\to$ C++rs::FnRef<R(...)>&mut dyn FnMut(...) -> R / impl FnMut(...) -> RBorrowed mutable, zero allocation
Rust $\to$ C++rs::Fn<R(...) const>Box<dyn Fn(...) -> R>Owned
Rust $\to$ C++rs::Fn<R(...)>Box<dyn FnMut(...) -> R>Owned mutable
Rust $\to$ C++rs::Fn<R(...) &&>Box<dyn FnOnce(...) -> R> / impl FnOnce(...) + 'staticOwned, single-use (std::move)
Rust $\to$ C++rs::DynCallable<Sig>(Rust callback in struct)Implicitly converts to absl::AnyInvocable<Sig>

Examples

Runnable, tested examples for both directions are in examples/types/callbacks/.