Try Embedded

Function pointers and callbacks

Callbacks, dispatch tables and the context pointer that makes them reusable.

Functions have addresses too

A function pointer holds the address of a function, so the function to call can be chosen at run time. That one idea is behind interrupt vector tables, callbacks, driver interfaces and state machines.

The declaration syntax is the hard part. Read it from the name outwards: int (*op)(int, int) says op is a pointer to a function taking two ints and returning int. A typedef makes it readable.

#include <stdio.h>
#include <stdint.h>

typedef int32_t (*binary_op_t)(int32_t, int32_t);

static int32_t add(int32_t a, int32_t b) { return a + b; }
static int32_t sub(int32_t a, int32_t b) { return a - b; }

static int32_t apply(binary_op_t op, int32_t a, int32_t b) {
  return op(a, b);              // call through the pointer
}

int main(void) {
  binary_op_t op = add;         // a function name decays to its address
  printf("%d\n", apply(op, 7, 3));
  op = sub;
  printf("%d\n", apply(op, 7, 3));
  return 0;
}

add and &add are the same value, and op(a, b) and (*op)(a, b) are the same call.

Pitfall: Without the parentheses, int *op(int, int) declares a function that returns int *. The parentheses around *op are what make it a pointer.

Callbacks

A callback is a function you hand to another module so that it can call you back when something happens. The module does not need to know who is listening, which keeps drivers independent of application code.

#include <stdio.h>
#include <stdint.h>
#include <stddef.h>

typedef void (*rx_callback_t)(uint8_t byte, void *context);

static rx_callback_t on_rx;
static void *on_rx_context;

static void uart_set_callback(rx_callback_t cb, void *context) {
  on_rx = cb;
  on_rx_context = context;
}

// Stands in for the receive interrupt.
static void uart_isr(uint8_t byte) {
  if (on_rx != NULL) on_rx(byte, on_rx_context);
}

typedef struct { uint32_t count; uint32_t sum; } stats_t;

static void count_bytes(uint8_t byte, void *context) {
  stats_t *s = context;
  s->count++;
  s->sum += byte;
}

int main(void) {
  stats_t stats = { 0, 0 };
  uart_set_callback(count_bytes, &stats);
  uart_isr(10);
  uart_isr(20);
  uart_isr(30);
  printf("%u bytes, sum %u\n", stats.count, stats.sum);
  return 0;
}

Two details are worth copying:

  • Check for NULL before calling. Jumping through a null function pointer on a Cortex-M ends in a HardFault.
  • Pass a context pointer. The void * lets the callback reach its own state without a global variable, so the same callback can serve two UARTs. It is C's substitute for a closure.

Dispatch tables

An array of function pointers indexed by a number replaces a long switch. The table is data: it can be const, so it lives in flash, and adding an entry does not touch the dispatch code.

#include <stdio.h>
#include <stdint.h>

static void cmd_status(void) { printf("status: ok\n"); }
static void cmd_reset(void)  { printf("resetting\n"); }
static void cmd_version(void) { printf("v1.2.0\n"); }

typedef void (*handler_t)(void);

static const handler_t handlers[] = { cmd_status, cmd_reset, cmd_version };
#define HANDLER_COUNT (sizeof handlers / sizeof handlers[0])

static void dispatch(uint8_t opcode) {
  if (opcode >= HANDLER_COUNT) {          // never index a table with an unchecked value
    printf("unknown opcode %u\n", opcode);
    return;
  }
  handlers[opcode]();
}

int main(void) {
  dispatch(2);
  dispatch(0);
  dispatch(9);
  return 0;
}

An unchecked index into a table of function pointers is a jump to an arbitrary address, so the bounds check is not optional. The interrupt vector table at the start of a Cortex-M image is exactly this structure, indexed by exception number.

A table of structs pairs each function with its metadata. This is the usual shape of a command-line shell:

typedef struct {
  const char *name;
  int (*handler)(int argc, char **argv);
  const char *help;
} command_t;

State machines

One of the most important uses of function pointers is the state machine where each state is a function and the object stores a pointer to its current state's handler: dispatching an event is one indirect call, and each handler contains only the events its state cares about. State machines have their own module in stage 5 (firmware architecture), which compares this form with the switch and table forms. This lesson's practice problems include two state machines built on function pointers: a pure transition function and a set of state handlers.

Common mistakes

  • Calling a function pointer that may be NULL.
  • Indexing a dispatch table with a value that came from outside without checking its range.
  • A callback type that does not match the function assigned to it. Calling through a mismatched pointer is undefined behaviour.
  • Doing long work inside a callback that runs in interrupt context.

Interview question: How does a microcontroller know which function to run when an interrupt occurs?

Answer: Through the vector table, an array of function addresses at a fixed location, normally the start of flash. Each exception and interrupt number indexes one entry. When the interrupt is taken, the CPU saves context, loads the address from the table and jumps to it. The first two entries on a Cortex-M are the initial stack pointer and the reset handler, which is how the device starts running your code.

In the product: a remote control

Each key of the remote maps to an action through a table of function pointers: a new model is a new table, not a new switch statement.

#include <stdio.h>

static int volume = 10;
static void vol_up(void) { volume++; printf("volume %d\n", volume); }
static void vol_down(void) { volume--; printf("volume %d\n", volume); }
static void power(void) { printf("power toggled\n"); }

struct key { int code; void (*action)(void); };

int main(void) {
  struct key keys[] = { { 0x10, vol_up }, { 0x11, vol_down }, { 0x0C, power } };
  int pressed[] = { 0x10, 0x10, 0x0C, 0x55 };
  for (int i = 0; i < 4; i++) {
    int found = 0;
    for (int k = 0; k < 3; k++)
      if (keys[k].code == pressed[i]) { keys[k].action(); found = 1; }
    if (!found) printf("key 0x%02X does nothing\n", pressed[i]);
  }
  return 0;
}

Build it: light effects chosen by name

This is step 3 of the module project. The phone app sends the lamp an effect by name: "steady", "blink", "breathe". A long if/else chain would grow with every new effect; instead the lamp keeps a table of names and function pointers, and adding an effect is one line in the table.

Lab: A table of effects as function pointers

An effect is a function uint8_t effect(uint32_t t_ms) returning the brightness (0 to 255) at time t_ms.

  • steady(t): always 200.
  • blink(t): 255 for the first 500 ms of every second, 0 for the rest.
  • breathe(t): rises from 0 to 255 over the first 1000 ms of every 2000 ms and falls back over the next 1000 ms. With p = t % 2000: p * 255 / 1000 while p < 1000, else (2000 - p) * 255 / 1000.

Fill the table EFFECTS[] with the three names and functions, then write:

  • lamp_set_effect(name) looks the name up in the table (compare with strcmp), makes it the current effect and returns true; an unknown name returns false and keeps the current effect. The lamp starts with steady.
  • lamp_brightness(t) calls the current effect through its pointer.

Going deeper

Interview question: How would you make one remote-control firmware serve ten different TV models?

Answer: Keep everything model-specific in data: a key table mapping each button to an action and an IR code set per model, chosen at pairing time and stored in flash. The engine (scan the keypad, debounce, look up, transmit, sleep) is shared and tested once. Adding a model is adding a table, which can even be downloaded, and the code that runs is the same for all of them.

Interview question: How would you write a typedef for a callback that takes a context pointer and an event code and returns nothing?

Answer: typedef void (*event_cb_t)(void *context, uint32_t event); Then a registration function stores both the callback and the context: void timer_on_expiry(timer_t *t, event_cb_t cb, void *context);. The caller passes its own object as the context and gets it back on each call, so one function can serve many instances without globals.

Interview question: What are the risks of calling a function pointer that came from data, such as a table indexed by a received byte?

Answer: An unchecked index can read past the end of the table and call whatever address is there, which can crash or execute arbitrary code if the data is attacker-controlled. Check the index range before using it, keep tables const so they live in flash and cannot be overwritten, and check for NULL entries. In safety-related code also protect against corrupted function pointers, for example by validating them against a known list.

Explain it: In your own words, explain how a dispatch table replaces a long switch statement.

Answer: Instead of a switch with one case per command, you build a constant array where each entry pairs a key, such as a command number or name, with a pointer to the function that handles it. To dispatch, you look up the key, by index or by searching the table, and call the function through its pointer. Adding a command means adding one table entry, the table can live in flash, and the dispatch code stays the same size however many commands there are.