2015年1月15日 星期四

[C/C++] Function Pointer

Every variables you declare in the program are stored in memory. In other words, there is an unique memory address for every variables. It is as same as the function even main function. Every functions have their own memory address.

For example:
void KeyFuncForA(char *OutputString)
{
 printf("A: %s\n", OutputString);
}
If we can use variable pointers to access memory to get the variables' value, we can also use function pointers to access memory to do a function call. And there are three important things you should know.
  1. The function return type.
  2. The parameter type.
  3. The number of parameter.
Above are used to declare a function pointer correctly. That's say if we want to declare a function pointer pointing to a function called "TestFunc". And the prototype of the function "TestFunc" is as below:
int TestFunc (unsigned char *ucPtr, char *String); // Prototype of function "TestFunc".

Now, we declare a function pointer called "FuncPtr" to point the function "Test Func":
int (*FuncPtr)(unsigned char*, char *); // Function pointer declaration.

After that, we can use the function pointer "FuncPtr" to point the function we want to use it, and this is how we can do:
FuncPtr = TestFunc; // Make "FuncPtr" point to function "TestFunc".
FuncPtr(0xFF, "Hello!"); // Make a function call. 
To be continue...

沒有留言:

張貼留言