c - 在 C 中的回调中传递参数

标签 c

<分区>

Possible Duplicate:
How do function pointers in C work?

stackoverflow 上冲浪我找到了这个例子:

/* Validation functions start */
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);
    ...
}

我想知道,假设 getNextRandomValue 有一个参数 getNextRandomValue(int i),我将如何包含它并使函数接受输入?

非常感谢

最佳答案

通常的做法是将指向“数据”的指针与函数一起传递。当函数被调用时,将该“数据”指针传递给函数并假设函数本身知道如何处理该数据。实际上,数据通常是指向结构的指针。所以代码看起来像这样:

struct func1_data {
    int a;
    int b;
};

struct func2_data {
    char x[10];
};

int function1(void *data) {
    struct func1_data *my_data = (typeof(my_data)) data;
    /* do something with my_data->a and my_data->b */
    return result;
}

int function2(void *data) {
    struct func2_data *my_data = (typeof(my_data)) data;
    /* do something with my_data->x */
    return result;
}

假设我们有

int caller(int (*callback), void *data) {
    return callback(data);
}

然后你这样调用所有这些:

struct func1_data data1 = { 5, 7 };
struct func2_data data2 = { "hello!" };
caller(function1, (void *) &data1);
caller(function2, (void *) &data2);

关于c - 在 C 中的回调中传递参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14270846/

相关文章:

c - allOddBits 返回 1

c++ - 在 gcc 中使用结构作为 SSE vector 类型?

c++ - 如何设置方边线api窗口

c - 系统调用返回值和errno

c - 为 PCB 应用程序生成加载时间序列号

c - 修复与通用指针相关的警告

控制台不等待输入。 (C语言)

c - 从函数返回 char** 时出现段错误

arrays - 哈希表和碰撞计算结果

c - 从父字符串中获取子字符串