Translate

Function callbacks in C

Ever since I started programming in Javascript, and doing asynchronous function calls, I’ve found myself to be addicted to passing functions as parameters.

I do it a lot in python and php, it’s very easy to do this on all these dynamic typed languages.

I never had this concept of passing functions as parameters, or pointers to functions as parameters when I was a kid in school and we were doing stuff in C or Pascal, I’d deal with it with ifs and switches.

So, this afternoon I decided to read a little bit and give it a try in C.

Here’s some code for future reference If I ever need it, it’s pretty easy.

#include 
void this() { printf("This\n"); }
void that() { printf("That\n"); }

int sum(int x, int y) {	return x+y; }

int mul(int x, int y) { return x*y; }

//Function that takes a callback that uses no parameters
void callanother(void (*callback)()) {
  (*callback)();
}

//Function that takes a callback that
//takes 2 int parameters and returns int
int callComplexCallback(int (*callback)(),int a, int b) {
  return (*callback)(a,b);
}

int main (int argc, char** argv) {
  callanother(this);
  callanother(that);

  printf("\n");

  int w = 20;
  int h = 30;

  printf("%d\n",callComplexCallback(sum,w,h));
  printf("%d\n",callComplexCallback(mul,w,h));

  //this also works
  printf("%d\n",callComplexCallback((*sum),w,h));
  printf("%d\n",callComplexCallback((*mul),w,h));

  return 0;
}

The output is this:

~$ ./a.out
This
That

50
600
50
600

The whole trick is how you define the function that will take the other function as a parameter.

If you have a function:

void whatever();

The function that’s supposed to use “whatever()” like-functions should look:

void useWhateverLikeFunctions(void (*f)()) {
  ...
  (*f)();
}

If you have a callback function that needs parameters, then you define the caller as:

void callerFunction(void (*f),int paramA, int* paramB, char paramC) {
  ...
  (*f)(paramA,paramB,paramC);
}

Then you’d use the function

void someCallback(int a, int* b, char c);

...
callerFunction(someCallback,a,b,c);
...

I know this is the oldest thing in the world to C programmers, but it never crossed my mind before, so here it is for my own personal reference, I hope it serves others.

Digg This
Reddit This
Stumble Now!
Buzz This
Vote on DZone
Share on Facebook
Bookmark this on Delicious
Kick It on DotNetKicks.com
Shout it
Share on LinkedIn
Bookmark this on Technorati
Post on Twitter
Google Buzz (aka. Google Reader)

Leave a Reply