Some concepts of function Pointers

  • 2020-04-02 01:44:47
  • OfStack

A function pointer

Looking at the source of android camera recently, I found a lot of call back and multi-threading. It is necessary to review the basis of it: function pointer, I think function pointer is mainly used in call back function and multi-threaded multi-process programming. When a function is compiled by the compiler, it is a bit of binary code with an entry address that is the value of the function pointer.

So let's look at the syntax of a function pointer, and for the simplest example, if you want to create a function pointer, it should be the same as the function it points to, in terms of the number of arguments, the type, and the return value.

Int a(Int a) {return a; }
Int (b)(Int n); // function pointer
B = a; // assigns a value to a function pointer
// you can also use b = &a; You can print the values of a and &a, which are actually the same
// int (*b)(int b) = a;
B (1); // the effect is the same as a(1).
// you can also use (*b)(1), the above method is standard c++, the annotation is to be compatible with c, can print the value of b and *b, is actually the same.

In addition, typedef is often used together with function Pointers, because there are too many parentheses for function Pointers, especially when it involves functions of class members. Therefore, in order to facilitate the use of typedef:
Typedef int (*b)(int n);
B, b1;
B1 = a; // is the same thing as int (b1)(int n) = a;

In call back, it is typical to pass in the function pointer that needs to call back, and then call the function that needs to call back according to the function pointer:
Int func(b callback, int num)
{
Return callback(num) * num;
}

In addition to the ordinary single function pointer, there can also be an array of function Pointers:
B array [10] = {a1, a2, a3... } // is actually int (*b[10])(int n); [] is a higher priority than *
Array [0] (1);


Related articles: