什么是"回调"在C和它们是如何实现的? [英] What is a "callback" in C and how are they implemented?

查看:214
本文介绍了什么是"回调"在C和它们是如何实现的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是新的C,Objective-C的,并在OSX核心音频节目。从我所做的阅读,核心音频很大程度上依赖于回调(和C ++,但那是另一回事)。我明白建立一个由另一个函数调用的重复完成任务函数的概念(在某种程度上)。我只是不明白它们是如何被建立,他们是如何工作的。任何例子是AP preciated。谢谢你。

I am new to C, Objective-C, and Core Audio programming on OSX. 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. Thanks.

推荐答案

有在C中没有回调 - 没有比任何其他泛型编程概念的更多

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);
    ...
}

在这里, populate_array 函数有一个函数指针作为其第三个参数,调用它来获取值来填充数组。我们已经写回调 getNextRandomValue ,它返回一个随机杂交的价值,并通过一个指向它 populate_array populate_array 将调用回调函数10次,将返回的值给定的数组中的元素。

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.

这篇关于什么是&QUOT;回调&QUOT;在C和它们是如何实现的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆