gpt4 book ai didi

c - 如何调用传递给另一个函数的任意 C 函数?

转载 作者:太空宇宙 更新时间:2023-11-03 23:34:32 24 4
gpt4 key购买 nike

我正在编写一个单元测试框架(有关详细信息,请参阅 SO)。或在 GitHub 查看代码.

Safer Code描述了一种传递任意类型函数的方法。

但是我如何在事先不知道它的类型的情况下调用这样的函数呢?假设 f 不需要输入,所以 f() 应该自己工作。

假设我想使用任意生成器函数填充一个数组。

void* gen_array(fp gen, size_t size) {
int i, len = gen_int() % 100;

void* arr = GC_MALLOC(len * size);

for (i = 0; i < len; i++) {
arr[i] = gen(NULL);
}

return arr;
}

它应该看起来像这样,但我收到编译器错误:

gcc -o example example.c qc.c qc.h -lgc
In file included from example.c:1:
qc.h:21: error: expected declaration specifiers or ‘...’ before ‘size_t’
In file included from qc.c:1:
qc.h:21: error: expected declaration specifiers or ‘...’ before ‘size_t’
qc.c:23: error: conflicting types for ‘gen_array’
qc.h:21: error: previous declaration of ‘gen_array’ was here
qc.c: In function ‘gen_array’:
qc.c:29: warning: dereferencing ‘void *’ pointer
qc.c:29: error: too many arguments to function ‘gen’
qc.c:29: error: invalid use of void expression
qc.h:21: error: expected declaration specifiers or ‘...’ before ‘size_t’
make: *** [example] Error 1

最佳答案

经过更多思考后,我意识到您的问题,您的上述代码将永远无法运行。您首先调用尝试调用一个没有参数且参数为 NULL 的 void 函数。接下来你需要你的代码更通用。我在下面举了一个例子来说明我的意思。现在使用全局变量

#include <stdio.h>
#include <stdlib.h>

typedef void (*fp)(void);


void * GEN_ARRAY_TEMP;

int gen_int() {
return 67;
}

void* gen_array(fp gen, size_t size) {
int i, len = gen_int() % 100;

void* arr = malloc(len * size);
void* arr_end = arr + len * size;
GEN_ARRAY_TEMP = arr;

while (GEN_ARRAY_TEMP <= arr_end) {
gen();
GEN_ARRAY_TEMP+=size;
}
return arr;
}

void make_int() {
(*(int*)GEN_ARRAY_TEMP) = 9;
}

int main() {
int i;
int * gen_int_array = (int*) gen_array(make_int, sizeof(int));
for(i=0;i<67;i++) {
printf("%d\n",gen_int_array[i]);
}
}

关于c - 如何调用传递给另一个函数的任意 C 函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7523358/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com