c, add multiple hooks in a function

Thread Starter

bug13

Joined Feb 13, 2012
2,002
Hi guys

I am in the process of learn/try to make my code more readable and organized. One thing I think it may be very useful is have the ability to add multple hooks (callback) to a function.

Is there a way to do this? Thanks guys!

That's what I would normally do:
Code:
void onEvent(function_ptr_t user_func1, function_ptr_t user_func2){
  // do regular stuff for this event
  regular_stuff();
  // do user stuff
  user_func1();
  user_func2();
}
Can we do something like this (similar to Java and C#):
Code:
void onEvent(void){
  // do regular stuff for this event
  regular_stuff();
  // do user stuff
  some_list = getUserHook();
  while (some_list != null){
    // do stuff in the list one by one
  }
}

// on other part of the code, or maybe different source file
void addEventHook(function_ptr_t func){
  // add to a hook list (assuming list is not full, for simplicity)
}
 

MrSoftware

Joined Oct 29, 2013
2,273
Is your intention for your some_list to actually be a list of functions that get called? If yes, you can do it with function pointers. Make your some_list an array or linked list of function pointers, then call them each inside your while loop. If you're using C++ then you can use a vector or list object (nice summary of differences here) and an iterator. Your addEventHook() can just add items to the list or vector. Google for function pointer tutorials, a good tutorial will be more informative than what I can cram into a single forum post.

You can also do it with event handlers like the other languages (C++, not C):

https://docs.microsoft.com/en-us/cpp/cpp/event-handling-in-native-cpp?view=vs-2017

Basically there are a number of ways you can do it, more than one right answer. :)
 
Last edited:

bogosort

Joined Sep 24, 2011
696
Hi guys

I am in the process of learn/try to make my code more readable and organized. One thing I think it may be very useful is have the ability to add multple hooks (callback) to a function.

Is there a way to do this? Thanks guys!
One way to do it in C is with a dispatch table, e.g., something like:

C:
// array of pointers to functions that take an int and return an int
int (*handler[])(int request) = { handle_open, handle_update, handle_close, NULL };

int main(void)
{
  int res = 0, i = 0;

  while ( handler[i] != NULL )
     res += handler[i++](0);

  printf( "result: %d\n", res ); // prints 6
  return 0;
}

int handle_open(int r)
{
  return r + 1;
}

int handle_update(int r)
{
  return r + 2;
}

int handle_close(int r)
{
  return r + 3;
}
 
Top