An instance of a callback function in C

  • 2020-04-02 02:18:18
  • OfStack

  In C language, typedefs are commonly used to define aliases (parameter names) for callback functions. An alias is implemented with a macro definition of a typedef, not a simple macro substitution. Can be used to declare multiple objects of pointer type at the same time.

Such as:


char *pa . pb ; //Pa is a char pointer, but pb is a char character. We can do it this way
typedef char* PCHAR ; 
PCHAR pa . pb ; //pa and pb Are all char A pointer type 

Let's look at an example of a callback function:

#include<stdio.h>
//Method pointer format: int (* PTR)(char *p) that is: return value (pointer name)(parameter list)
typedef int (*CallBackFun)(char *p);    //Name the callback function, type CallBackFun, and parameter char *p
//Method Afun, formatted in the format of CallBackFun, can be thought of as a callbackfun&sponge; & have spent
int Afun(char *p)
{
    printf("Afun  Callbacks print out characters %s!n", p);   
    return 0;
}
//The method Cfun, whose format conforms to the CallBackFun format, can therefore be considered a CallBackFun
int Cfun(char *p)
{   
    printf("Cfun  The callback to print :%s, Nice to meet you!n", p);   
    return 0;
}
//Perform the callback function, way 1: by naming it, pCallBack can be thought of as an alias for CallBackFun
int call(CallBackFun pCallBack, char *p)
{   
    printf("call  Print out the characters directly %s!n", p);   
    pCallBack(p);   
    return 0;
}
//Execution of the callback function, way two: directly through the method pointer & PI; & have spent & have spent
int call2(char *p, int (*ptr)())  //Or int call2(char *p, int (* PTR)(char *)) and PTR can be arbitrarily named
{
    printf("==============n", p);    
    (*ptr)(p);
}
int main()
{   
    char *p = "hello";
    call(Afun, p);   
    call(Cfun, p);
    call2(p, Afun);   
    call2(p, Cfun);
    return 0;
}
 Take another 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 %sn",(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 case, the type of the callback function's argument is defined by the caller (repeat), and the implementer (hello,count) is a void pointer. The implementer is only responsible for passing the pointer to the callback function, and does not care what data type it points to. The caller knows that the argument he passes is a char, so he should know that the argument is to be converted to a char * in the callback function he provides.


Related articles: