这是问的问题: What is a “callback” in C and how are they implemented?
那个问题的答案之一是这样的: (我稍微修改以打印该值)
#include <stdio.h>
#include <stdlib.h>
void populate_array(int *array, size_t arraySize, int (*getNextValue)(void))
{
for (size_t i=0; i<arraySize; i++) {
array[i] = getNextValue();
printf("%d\n", array[i]); // This is what I added
}
}
int getNextRandomValue(void)
{
return rand();
}
int main(void)
{
int myarray[10];
populate_array(myarray, 10, getNextRandomValue);
}
现在我的问题是上面的回调函数有什么用,什么时候我也可以不用回调来做?
#include <stdio.h>
#include <stdlib.h>
void populate_array(int *array, size_t arraySize, int getNextValue(void))
{
for (size_t i=0; i<arraySize; i++) {
array[i] = getNextValue();
printf("%d\n", array[i]);
}
}
int getNextRandomValue(void)
{
return rand();
}
int main(void)
{
int myarray[10];
populate_array(myarray, 10, getNextRandomValue);
}
另外,能否请您给我一个简单函数无法完成的回调函数的真实示例?
最佳答案
Now my question is the what is the use of callback function in above, when I can do it without callback also?
没什么,真的 - 这不是一个真实的例子,它只是为了解释回调是如何工作的。
Also, can you please give me real example of callback function which cannot be done with simple function?
cURL library当它需要用户提供数据时(例如,当发出 HTTP POST 请求时)或当它想要通知用户数据检索时(例如,当服务器发送 HTTP header 时),使用读、写和各种其他回调函数.虽然这可以使用临时缓冲区、动态内存分配和“属性 setter ”函数来完成,但使用回调函数方法更方便(即需要更少的跑腿)。
关于回调函数误解,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17747369/