C/pointer to function
Expert: Narendra - 6/16/2006
Question
Thanks Narendra,
can u tell me what is callback mechanism?
where it is used.
-------------------------
Followup To
Question -
Hello Narendra,
IS function pointer and pointer to function both are same ?
explain me function pointer details with a function example.
Thanking you
Answer -
Yes both are same.
It is also like any other pointer, which can hold address.
In this case, it holds the address of a function.
And you can use this pointer to call that function instead of calling it directly. i.e, you are indirectly calling the function.
The beauty of this is, you can use the same pointer to call different functions. Just replace the address with new function.
And this is used for implementing callback mechanism.
I think any book on C programming/pointers will explain this and gives examples.
You can refer them for more information.
AnswerCallback is used in cases, where there is heirarchy.
In that type of systesm, you can make call from higher level to lower level, but not from lower level to higher level.
Say you have a TCP stack. You can make calls from application layer to other layers. But not from other layers to application layer.
But, in some situation you will need to do this. This is achieved using callback mechanism.
Here is a simple example to show the usage:
Assume we have 3 functions level1(), level2() and level3()
level1() - This is the function exposed to outside world.
level2() - Lower level function operating on actual data. But, this may not know the details of what is the data.
level3() - This functions knows about the data also.
Here is the prototype of these functions:
typedef struct {
....
} data;
level3( data_s *p )
{
/*
* Process the data
*/
}
level2( void (*fun)(data*) )
{
/*
* Call the function level3() indirectly
* to process the data.
*/
fun->(data);
}
level1()
{
/*
* Call level2() to process data
*/
level2(level3);
}
The advantage of this mechanism is that it provides a level of indirection to the function level2() which is helpful to make it data independent. If you were to implement the same logic to process different type of data-structures, then the code size increases creating maintanance problems.
You must have used qsort() function. This uses this callback mechanism. It's prototype is:
void qsort(void *base, size_t nel, size_t width, int
(*compar)(const void *, const void *));
Any sorting needs a swap function. How to make this accept all data types?
This is achieved by using a level of indirection.
In simple words, we can say that the callback mechanism involves a function which is passed the address of another function; and the called function calls the passed funciton.
Hope this is clear now.
You can refer the following link for more information:
1.
http://www.codeguru.com/cpp/cpp/cpp_mfc/callbacks/article.php/c10557/