Callback
How do you actually implement a callback from scratch in C++? I use lots of callbacks through ROS, but I have not reasoned through how callbacks are implemented.
I know you pass in a Function Pointer, but under the hood, what happens?
Callbacks are generally used in asynchronous communication scenarios, where you don’t want a thread to be blocked.
In C
I was asked this for my Apple interview. I wasn’t familiar with the syntax of a C-style callback
- https://stackoverflow.com/questions/142789/what-is-a-callback-in-c-and-how-are-they-implemented
- https://primerpy.medium.com/functional-pointer-and-callback-in-c-86c208df6b2f
Here is an example of callbacks in C.
Let’s say you want to write some code that allows registering callbacks to be called when some event occurs.
First define the type of function used for the callback:
Now, define a function that is used to register a callback:
This is what code would look like that registers a callback:
In the internals of the event dispatcher, the callback may be stored in a struct that looks something like this:
This is what the code looks like that executes a callback.