liveBook · Manning

Callback

As explained in Embedded Software with Rust

A callback is a function supplied to another component so that component can invoke it later in response to a particular condition or event.

A callback is a function registered with another component so it can be invoked later when a particular event occurs. In embedded C libraries, this can connect an event such as a received UART byte to Rust code. section 8.4.2

// callback_lib.h
#ifndef CALLBACK_LIB_H
#define CALLBACK_LIB_H

// A type alias for "a function that takes an int and returns nothing."
// This is what a callback looks like from C's point of view: just a
// pointer to a function with this signature.
typedef void (*callback_t)(int);

// Lets someone hand this library a function to call later.
void register_callback(callback_t cb);

// Fires whichever function was last registered, passing it `value`.
void trigger_callback(int value);

#endif

The C declaration uses a function pointer for the callback and provides a registration function for storing it. section 8.4.2

Calling a Rust callback from C

A Rust function declared with the C calling convention can be registered with the C library. The library invokes it later when its event occurs; registration itself does not trigger the callback. section 8.4.2

How Embedded Software with Rust covers it

How deep it goes
Demonstrates registration and triggering across a C-Rust boundary, while deferring callbacks with context.
Examples
Uses UART byte arrival, timer expiration, and sensor readings as events that can trigger callbacks.
What you can do after
Build it from scratch by declaring a C-compatible Rust function and registering it with a C library.
How it connects
Connects callbacks to FFI and C function pointers.

Also explained in

Compare how 23 books explain callback →

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.