thelonepole.com - The Lone Pole

Description: CS/CE/EE blog. Hardware. Software. Math.

Example domain paragraphs

In C functions are generally not considered first-class objects. Although pointers to functions exist and can be used to build some routines that have rudimentary higher-order behavior, there is no language syntax for dynamically creating a long-lived function at run time, partially evaluating a function, creating a closure, etc. But as we can build interpreters for higher level languages that do support this, surely there must be a way to achieve this?

A basic use-case for passing a function to another in C is a situation where we have asynchronous events that require notification. To solve this, we typically create a function called a callback to register with some kind of event-generating framework to notify us of these asynchronous events. Furthermore we likely want some kind of context to go along with the function, so that the same function definition could be used with multiple different context objects to handle different events.

If we have control of both sides of the API, then we could define a callback interface where we register a function which takes an additional parameter representing this context information. This is a common C idiom: in the real world it is used in the Linux kernel to register interrupt handlers so that they can be called with a pointer to the struct device that they need to actually handle the interrupt (interrupt handlers have two parameters, however, not just one, because they also include the interrupt