gcc 4.4.3 c89
I am creating a client server application and I will need to implement some callback functions.
However, I am not too experienced in callbacks. And I am wondering if anyone knowns some good reference material to follow when designing callbacks. Is there any design patterns that are used for c. I did look at some patterns but there where all c++.
Many thanks for any suggestions,
Here is a very rough example. Please note, the only thing I’m trying to demonstrate is the use of callbacks, its designed to be informational, not a demonstration.
Lets say that we have a library (or any set of functions that revolve around a structure), we’re going to have code that looks similar to this (of course, I’m naming it foo):
That’s simple enough. We’d then (conventionally) provide some means of allocating and freeing it, such as:
And then:
But we want a callback, so we can define a function that will be entered when
foo->texthas something to report. To do that, we use a typed function pointer:We also want any of the
foofamily of functions to be able to enter this callback conveniently. To do that, we need to add it to the structure, which would now look like this:Then we write the function that will actually be entered (using the same prototype of our callback type):
We then need to write some convenient way to say what function it actually points to:
And then our other foo functions can use it, for instance:
Note that in the above:
Is just like doing this:
Except that, we enter
my_foo_callback()via a function pointer that we previously set, thereby giving us the flexibility to define our own handler on the fly (and even switch handlers if / as needed).One of the biggest problems with callbacks (and even the code above) is type safety when using them. A lot of callbacks will take a
void *pointer, usually named something likecontextwhich could be any type of data/memory. This provides great flexibility, but can be problematic if your pointers get away from you. For instance, you don’t want to accidentally cast what is actually astruct *aschar *(orintfor that matter) by assignment. You can pass much more than simple strings and integers – structures, unions, enums, etc can all be passed. CCAN’s type safe callbacks help you to avoid unwittingly evil casts (to / fromvoid *) when doing so.Again, this is an over simplified example that’s designed to give you an overview of one possible way to use callbacks. Please consider it psuedo code that is meant only as an example.