Function Pointers

 

Function Pointers are a special kind of pointer that allow you to hold the address of a particular function and call it at runtime. Because function pointers are variables, the functions they point to can change over time. This allows us the freedom to make extremely flexible applications.

For the moment though, a basic example :


/* define two functions */
void func1(void) { printf("1\n"); }
void func2(void) { printf("2\n"); }

/*
* this defines a 'type' of function. The general form is
* <return type> (*func_type_name)( <arg list> )
*
* The following pointer is to a function that accepts
* void and returns void
*/

typedef void (*FuncType)( void );

/* create a function pointer */
FuncType MyFunction;

/* store func1 in the function variable */

MyFunction =
func1;

/* call the function */

MyFunction();

/* store function 2 in MyFunction */

MyFunction = func2;

/* call the function */

MyFunction();


 

A function pointer essentually holds an address where the intsruction pointer of the process will move to.

 

 

Further Reading :

 

With large complex libraries such as user interface libraries etc, you will often find that they use the concept of CALLBACK functions, or the storage of functions as types. For example, we have already seen this with glut and the idea that glut will call OUR function.

PUI uses callback functions extensively to provide the action to perform when a control is clicked or altered in some way. I would doubt that you would need to create your own function pointers for the type of application generally produced at the NCCA, however the chances are you will be using a library that uses them extensively.

For some code examples on function pointers, have a look at the CommandLine code samples that illustrates a very basic command line idea using arrays of function pointers. You may also want to pay particular attention to the Menu example in PUI.