C - callback                                                                                                  Home : www.sharetechnote.com

 

 

 

 

Callback/Function Pointer

 

Callback is a mechanism to pass a function (not a value) to another function as an argument. Most of the readers who has even a little bit of programming experience creating a function. But almost of all (or every) functions that you have created would be the function without any parameter at all (or called function with void parameters) or function with value parameter (e.g, parameter in the form of int, char, char*, struct etc) and you may not know that you can pass a function as a parameter. It would be difficult to understand what it is if you don't try on your own. Just try a couple of examples shown here.

 

 

Example 1 > Callback function with no return (void return)

 

#include <stdio.h>

 

void PrintMsg()

{

    printf("Hello World");

}

 

// This function takes in a function as an argument

void RunCallBack(void (*ptrFunc)())

{

    

    ptrFunc();

    

}

 

int main()

{

    // The address of the function PrintMsg() is passed as an argument to RunCallBack()

    RunCallBack(&PrintMsg);

}

 

Result :----------------------------------

 

Hello World

 

 

Example 2 > Callback function with return

 

#include <stdio.h>

#include <stdlib.h>

#include <string.h>

 

char* PrintMsg()

{

    return "Hello World";

}

 

// This function takes in a function as an argument

void RunCallBack(char* (*ptrFunc)())

{

    

    char* msg;

    msg = (char *)malloc(255);

    

    strcpy(msg,ptrFunc());

        

    printf("%s",msg);

}

 

int main()

{

     // The address of the function PrintMsg() is passed as an argument to RunCallBack()

    RunCallBack(&PrintMsg);

}

 

 

Result :----------------------------------

 

Hello World

 

 

Example 3 > typedef callback function

 

#include <stdio.h>

 

typedef void (*callback)();  // now the void function point can be called as a new type called 'callback'

 

void PrintMsg()

{

    printf("Hello World");

}

 

void RunCallBack(callback ptrFunc)

{

    

    ptrFunc();

    

}

 

int main()

{

    RunCallBack(&PrintMsg);

}

 

Result :-----------------------

 

Hello World

 

 

Example 4 >  Array of Callback function

 

#include <stdio.h>

#include <time.h>

 

typedef void (*callback)();

 

void PrintMsg()

{

    printf("Hello World\n");

}

 

void PrintTime()

{

    

  time_t rawtime;

  struct tm * timeinfo;

 

  time ( &rawtime );

  timeinfo = localtime ( &rawtime );

  printf ( "Current local time and date: %s\n", asctime (timeinfo) );   

  

}

 

void RunCallBack()

{

    

    int i;

    callback aryCallback[2] = {PrintMsg, PrintTime};

    callback ptrFunc;

    

    for( i = 0; i < 2; i++ ) {

        ptrFunc = aryCallback[i];

        ptrFunc();

    }

    

}

 

int main()

{

    RunCallBack();

}