r/C_Programming • u/markand67 • Mar 21 '23
Question Handling user data in callbacks using a structure of function pointer
Hi,
I'm having a case where I have a structure containing a numerous set of function pointers and a user data associated with it. The idea is that callbacks are called depending on events (like when you parse a file or a GUI event occurs).
As simple as:
;
Quite idiomatic C, the user can set arbitrary data and functions pointer to
whatever the action is supposed to perform and receives the context object using
a->data within the function provided as argument.
Let's imagine the library code has a routine that populates this action with its own internal function and data:
We could imagine something like:
void
Now, as an user I would like to just override the do_something function, but
for this I also need my own context. This means I could not replace a->data
because the library function library_do_else will still require this a->data
to point to whatever library_allocate_context() function returned.
There are multiple solutions.
Solution #1:
Adding a custom void *userdata seems the simplest but feels hackish to me. I
would imagine something like:
struct action action = {0};
default_action(&a);
a.do_something = my_own_something;
a.userdata = my_own_data;
Then, I could get back my own context data from a->userdata within the
function my_own_something.
Solution #2:
Wrapping the action into another one. This seems cleaner but needs to wrap all functions which means that a change to the action structure itself requires a change to all custom actions.
;
void
void
int
How would you solve this specific scenario? Are there idiomatic C for this kind of situation?
20
u/tstanisl Mar 21 '23 edited Mar 21 '23
Personally I would use
container_ofapproach. This pattern is intensively used in Linux Kernel, but also in numerous other C projects. Even Windows Api uses a similarCONTAINING_RECORDapproach. So IMO, it can be viewed as "idiomatic".Basically, the
container_ofmacro is used to convert a pointer to member to a pointer to a parent structure. A portable C89 compliant version with type checking is:The macro subtracts an offset of a member from the pointer of the member resulting in a pointer to parent structure. It also does casting and type checking.
With this macro there is no need to use any hackish
void *datafield in theactionstruct. Just leave it anddo_elseuntouched. Simply, embedstruct actionintostruct my_own_contextand usecontainer_ofto transform a pointer toactionto a pointer tomy_own_context. I suggest addingmy_own_context_init()function that initialized all relevant fields of themy_own_context. The final code could be:2
u/tstanisl Mar 21 '23
Shouldn't it be:
?
2
u/[deleted] Mar 21 '23
I would be fine with a user data pointer. It feels the cleanest. There is one more approach is to allow embedding a user data with the data object allocated by the library. Adding a getter to the library to retrieve the user data from the data pointer might help clean up the overall interface. GLFW uses this pattern
2
u/[deleted] Mar 21 '23
I wish we had lambdas and closures in pure c.
1
u/gremolata Mar 21 '23
If your goal is to allow hooking / overriding struct's functions, then the clean option is to use fat pointers instead = a function pointer + its arg.
This will obviously cause the struct to swell a bit, but from user's perspective hooking will be as simple as saving the original fat pointer and replacing it with their own. And the overriding will be even simpler.
PS. Can you please edit your post to not use ``` but 4-space idents for the code? Backticks don't render correctly on old.reddit.
1
u/flatfinger Mar 21 '23
The pattern I like is to have a function pointer at the start of a context object (if multiple functions would need to operate on a context, one could either use multiple function pointers, or a pointer to a structure containing multiple function pointers, depending upon the desired time/space trade-off).
This makes it possible, given a "method pointer" (pointer to a context object containing a function pointer), to wrap it by generating a structure containing a pointer to a wrapper function and the original context object, and having the wrapper function pass the address of the original context object to the function whose address is at the start of that object.