Today, when reading the source code of Libcurl, we find that the method of defining function pointers is different from the usual way. Detailed analysis of a bit.
In Libcurl code, a set of function pointers that send data is defined. As shown below:
Code Catalog: Lib/urldata.hstruct connectdata {... Curl_send *send[2];.};
where curl_send is defined as follows:
Code Catalog: lib/urldata.h/* Return the count of bytes sent, or-1 On Error */typedef ssize_t (curl_send) (struct connectdata *c Onn,/* Connection data */ int sockindex,/ * Socketindex */ const void *BUF,/ * data to write */ Size_ T len,/ * Max amount to write */ curlcode *err); /* ERROR to return */
The confusion is that we usually use TypeDef to define function pointers, which are generally written in the following form:
Defines a function pointer that receives an shaping parameter and returns an integer value. typedef int (*PFUNC) (int);
However, the curl_send definition does not have a pointer symbol on it. After reviewing some information, it is possible to find such a definition method.
So, wrote the following program to verify a bit.
#ifdef __cplusplus#include <iostream> #else # include <stdio.h> #endifint testFunc (int para) {#ifdef __ Cplusplusstd::cout << "C + + parameter is:" << para << Std::endl; #elseprintf ("C parameter is:%d\n", para ); #endifreturn 0;} int main () {typedef int (PTESTFUNC) (int);p TestFunc *pfunc = testFunc; Mode 1:ok pfunc (1111); Mode 2:ok (*pfunc) (2222); Way 3:okptestfunc *PFUNC2 = &testFunc; Way 4:okpfunc2 (3333); return 0;}
If you save the above program as a C program file (. c), compile it to get the following results:
C parameter is:1111
C parameter is:2222
C parameter is:3333
If you save as a C + + program file (. cpp), you get the result:
C + + parameter is:1111
C + + parameter is:2222
C + + parameter is:3333
From the above results you can see:
1. It is also possible to use the same function declaration method as curl_send. As the definition of ptestfunc above.
2. For the initialization of the function pointer Pfunc, it is possible to use either of these methods. Refer to the above Way 1 with mode 4.
3. The call to function pointer Pfunc can also be used in different ways, referring to mode 2 and Mode 3.
Of course, we also use the traditional method of declaring function pointers, as shown in the following procedure:
int main () {typedef int (*PTESTFUNC) (int);p TestFunc pFunc = testFunc; Mode 5:okpfunc (1111); Mode 6:ok (*pfunc) (2222); Way 7:okptestfunc PFUNC2 = &testFunc; Way 8:okpfunc2 (3333); return 0;}
The result is exactly the same as described earlier.
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
c&c++ function pointer