Sunday, March 28, 2010

Generic Function Pointer Example

You can use any function pointer as a generic function pointer, however you need to typecast it properly before calling the actual function it points to.



#include <stdio.h>
/* This is our generic function pointer */
typedef void (*fp)(void);

int func1(int a)
{
printf("Inside Func 1. Received %dn",a);
return 2;
}
char func2(char b)
{
printf("Inside Func 2. Received %cn",b);
return 'b';
}
int main()
{
fp ptr1;
int temp1;
char temp2;

/* Typecast the original function to generic function pointer before assigining */

ptr1 = (fp) func1;

/* Typecast back to original function type before calling. The syntax to do this typecasting is quite convoluted though, as you can see. */

temp1 = ((int (*)(int)) ptr1)(1);
ptr1 = (fp) func2;
temp2 = ((char (*)(char))ptr1)('a');
printf("Inside Main. Received %d %cn", temp1, temp2);
return 0;
}



Output:
Inside Func 1. Received 1
Inside Func 2. Received a
Inside Main. Received 2 b