In C language, a typedef is generally used to define aliases (parameter names) for callback functions. Aliases are implemented through macro-defined TypeDef, not as simple macro substitutions. Can be used as multiple objects that declare a pointer type at the same time.
Like what:
Copy Code code as follows:
Char *pa,pb;//pa is a char pointer, but PB is a char character. We can do that.
typedef char* PCHAR;
Pchar Pa,pb;//pa and Pb are char pointers
Let's look at an example of a callback function:
Copy Code code as follows:
#include <stdio.h>
The format of the method pointer is: Int (*ptr) (char *p) that is: return value (pointer name) (argument list)
typedef int (*callbackfun) (char *p); Name the callback function, the type is named Callbackfun, and the parameter is char *p
Method Afun, the format conforms to the Callbackfun format, so it can be viewed as a callbackfun
int Afun (char *p)
{
printf ("Afun callback prints out character%s!\n", p);
return 0;
}
Method Cfun, the format conforms to the Callbackfun format, so it can be viewed as a callbackfun
int Cfun (char *p)
{
printf ("Cfun Callback printing:%s, nice to meet you!\n", p);
return 0;
}
Execute the callback function, one way: by naming, pcallback can be considered an alias for Callbackfun
int call (Callbackfun pcallback, char *p)
{
printf ("Call directly prints out character%s!\n", p);
Pcallback (P);
return 0;
}
Execute the callback function in two ways: directly through the method pointer
int Call2 (char *p, int (*ptr) ())//or int call2 (char *p, int (*ptr) (char *)) while PTR can be named arbitrarily
{
printf ("==============\n", p);
(*PTR) (p);
}
int main ()
{
char *p = "Hello";
Call (Afun, p);
Call (Cfun, p);
Call2 (P, afun);
Call2 (P, cfun);
return 0;
}
Let's look at an example of a callback function:
#include <stdio.h>
typedef void (*callback) (char *);
void repeat (callback function, char *para)
{
function (para);
function (para);
}
void Hello (char* a)
{
printf ("Hello%s\n", (const char *) a);
}
void Count (char *num)
{
int i;
for (i=1;i< (int) num;i++)
printf ("%d", I);
Putchar (' \ n ');
}
int main (void)
{
Repeat (Hello, "Huangyi");
Repeat (count, (char *) 4);
}
In this example, the parameter of the callback function is interpreted by the caller (repeat) as a void pointer, and the implementation is responsible for handing the pointer to the callback function, regardless of what data type it is pointing to. The caller knows that the parameter they are passing is char, and it should be explained in the callback function provided by the parameter to be converted to char * type.