How to explain callbacks in plain english? How are they different from calling one function from another function?

后端 未结 30 1914
时光说笑
时光说笑 2020-11-22 11:13

How to explain callbacks in plain English? How are they different from calling one function from another function taking some context from the calling function? How can thei

30条回答
  •  独厮守ぢ
    2020-11-22 11:16

    What Is a Callback Function?

    The simple answer to this first question is that a callback function is a function that is called through a function pointer. If you pass the pointer (address) of a function as an argument to another, when that pointer is used to call the function it points to it is said that a call back is made.

    Callback function is hard to trace, but sometimes it is very useful. Especially when you are designing libraries. Callback function is like asking your user to gives you a function name, and you will call that function under certain condition.

    For example, you write a callback timer. It allows you to specified the duration and what function to call, and the function will be callback accordingly. “Run myfunction() every 10 seconds for 5 times”

    Or you can create a function directory, passing a list of function name and ask the library to callback accordingly. “Callback success() if success, callback fail() if failed.”

    Lets look at a simple function pointer example

    void cbfunc()
    {
         printf("called");
    }
    
     int main ()
     {
                       /* function pointer */ 
          void (*callback)(void); 
                       /* point to your callback function */ 
          callback=(void *)cbfunc; 
                       /* perform callback */
          callback();
          return 0; 
    }
    

    How to pass argument to callback function?

    Observered that function pointer to implement callback takes in void *, which indicates that it can takes in any type of variable including structure. Therefore you can pass in multiple arguments by structure.

    typedef struct myst
    {
         int a;
         char b[10];
    }myst;
    
    void cbfunc(myst *mt) 
    {
         fprintf(stdout,"called %d %s.",mt->a,mt->b); 
    }
    
    int main() 
    {
           /* func pointer */
        void (*callback)(void *);       //param
         myst m;
         m.a=10;
         strcpy(m.b,"123");       
         callback = (void*)cbfunc;    /* point to callback function */
         callback(&m);                /* perform callback and pass in the param */
         return 0;   
    }
    

提交回复
热议问题