What is a "callback" in C and how are they implemented?

noizetoys picture noizetoys · Sep 27, 2008 · Viewed 298.7k times · Source

From the reading that I have done, Core Audio relies heavily on callbacks (and C++, but that's another story).

I understand the concept (sort of) of setting up a function that is called by another function repeatedly to accomplish a task. I just don't understand how they get set up and how they actually work. Any examples would be appreciated.

Answer

aib picture aib · Sep 27, 2008

There is no "callback" in C - not more than any other generic programming concept.

They're implemented using function pointers. Here's an example:

void populate_array(int *array, size_t arraySize, int (*getNextValue)(void))
{
    for (size_t i=0; i<arraySize; i++)
        array[i] = getNextValue();
}

int getNextRandomValue(void)
{
    return rand();
}

int main(void)
{
    int myarray[10];
    populate_array(myarray, 10, getNextRandomValue);
    ...
}

Here, the populate_array function takes a function pointer as its third parameter, and calls it to get the values to populate the array with. We've written the callback getNextRandomValue, which returns a random-ish value, and passed a pointer to it to populate_array. populate_array will call our callback function 10 times and assign the returned values to the elements in the given array.