Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/70.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C 如何在上层作用域中的回调中导出结构?_C - Fatal编程技术网

C 如何在上层作用域中的回调中导出结构?

C 如何在上层作用域中的回调中导出结构?,c,C,我有一个由共享库调用的回调。 我想通过param将结构结果导出到不同的范围: int process(int* result, void* param){ param = result; } // should be hidden by the lib, I only have the definition but for the test, here is it. int hiddenFunc(int (*f)(int*, void*), void* param){ int

我有一个由共享库调用的回调。 我想通过
param
将结构
结果
导出到不同的范围:

int process(int* result, void* param){
    param = result;
}

// should be hidden by the lib, I only have the definition but for the test, here is it.
int hiddenFunc(int (*f)(int*, void*), void* param){
    int cc = 155;
    f(&cc, param);
}

int main() {
    int *scopeint = NULL;
    hiddenFunc(&process, scopeint);
    printf("scopeint should point to cc and be 155 : %d", *scopeint);
}

为什么
scopeint
没有指向主函数末尾的
cc

scopeint
没有指向
main
末尾的
cc
,因为在将
scopeint
初始化为
NULL
后,您从未将任何内容分配给它

如果希望函数修改调用者中的变量,则需要传递指向它的指针

hiddenFunc(&processCallback, &scopeint);

*(int**)param = result;
一般来说,您还可以返回新值,并让调用者为您修改它

scopeint = hiddenFunc(&processCallback);
请注意,您正试图将
scopeint
设置为指向在
hiddenFunc
返回后不再存在的变量的指针。如果要“返回”指针,则需要将返回的值放在堆上,而不是使用自动存储

总的来说,这提供了三种解决方案,具体取决于分配
int
的三个函数中的哪一个

int process(int* result, void* param){
    int *r = malloc(sizeof(int));
    *r = *result;
    *(int**)param = r;
}

int hiddenFunc(int (*f)(int*, void*), void* param){
    int cc = 155;
    f(&cc, param);
}

int main(void) {
    int *scopeint;
    hiddenFunc(&process, &scopeint);
    printf("scopeint should point to cc and be 155 : %d", *scopeint);
    free(scopeint);
}


你的意思是像传递一个
**
这样回调就可以“返回”一个值?我用一种更简单的方式编辑过。process()为指针分配一个指针。我不需要**
scopeint
应该与
cc
具有相同的地址,即使您成功地更改了此代码(您需要更多的&s和更多的*s,正如人们所指出的),设置指向堆栈变量的指针仍将以问题告终。如前所述,hiddenFunc是隐藏的。对于这个问题,我将其定义为堆栈变量。我相信var在lib中是malloc'd,并且在调用
exit()
时被释放。谢谢<代码>测试现在是
scopeint
。它已经是一个指针,hiddenFunc需要一个指针,而不是指针的指针。我想在指针中指定cc的地址。名称无关紧要,指针就是指针,即使它指向指针。
int process(int* result, void* param){
    *(int**)param = result;
}

int hiddenFunc(int (*f)(int*, void*), void* param){
    int *cc = malloc(sizeof(int));
    *cc = 155;
    f(cc, param);
}

int main(void) {
    int *scopeint;
    hiddenFunc(&process, &scopeint);
    printf("scopeint should point to cc and be 155 : %d", *scopeint);
    free(scopeint);
}
int process(int* result, void* param){
    *(int*)param = *result;
}

int hiddenFunc(int (*f)(int*, void*), void* param){
    int cc = 155;
    f(&cc, param);
}

int main(void) {
    int scopeint;
    hiddenFunc(&process, &scopeint);
    printf("scopeint should point to cc and be 155 : %d", scopeint);
}