Tuesday, July 14, 2009

Function Pointers and Callback Functions

Pointer: It will hold the address of the varialbe.
*********

Function Pointer: It will hold the address of the function. and its notation is like this
****************
int (*func_ptr)();

Here if we not put a bracket it takes the function(func_ptr) going to return integer pointer.
For holding the address we need to use pointer symbol(*) -->(*func_ptr) and to avoid the
confusion we added the bracket(*func_ptr).

If we are using a funciton pointer to hold the address of another function means that function pointer must have same numbers of parameter and same type and the return type also
same.

Function Pointer Example:
************************
#include

void print()
{
printf("Called via Function pointer");
}
int main()
{
void (*func_ptr)(void);

func_ptr = print;
func_ptr();
return 0;
}


Usage of Function Pointers:
*************************
In a same place. if we need to call a multiple function in a different time we can use function pointers. Best example is uboot intialization sequence.

Uboot Initialization Sequence:
***************************
In the lib_ppc/board.c file line no:288

(http://git.denx.de/cgi-bin/gitweb.cgi?p=u-boot.git;a=blob;f=lib_ppc/board.c;h=155171d6b12fdfc47637f813eace6d3742e02141;hb=7d4450a9773673052fcd7fdf0a4a88c089126ac1)

we have an pointer array called(*init_sequence[] ). This array containg function for initalizing ram, flash, clock, watchdog timer, i2c, POST test etc ... Using a single function pointer(init_fnc_ptr) we are calling all the initialization funciton one by one and intializing all the pheriperals.

Ex:
for (init_fnc_ptr = init_sequence; *init_fnc_ptr; ++init_fnc_ptr) {
if ((*init_fnc_ptr) () != 0) {
hang ();
}
}

Callback Functions: Extension of function pointer is callback functions.
****************
We can register a function with the function pointer and called that function via function pointer when particular event happens thats why we called as call-back functions.

Simple example of callback function:
http://kerneltrap.org/node/8412

Realtime Usage:
**************
Best example is Win32 API programming. In that we will write a function for mouse left click and right click and register that function as callback functions. At the runtime if we right click the mouse that particualr right click call-back function will call.

In Linux we will use the callback function for registering interrupt etc ..

Syntax of request_irq:

int request_irq (unsigned int irq, void (*handler) (int, void *, struct pt_regs *), unsigned long irqflags, const char *devname, void *dev_id);

ret = request_irq(4, handler, SA_INTERRUPT, "serialport", handler);


In the above example, handler is a callback function, We are sending our own function to the request_irq, request_irq register this function with the function pointer, if interrupt happens our callback function(handler) will call via that particular function pointers.

Saturday, December 6, 2008