如何在上层范围的回调中导出结构?

  • 本文关键字:结构 回调 范围 c
  • 更新时间 :
  • 英文 :


>我有一个由共享库调用的回调。 我想通过以下方式将结构result导出到不同的范围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

scopeintmain末尾不指向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);
}

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

最新更新