我有一个由共享库调用的回调。我想通过param将结构result导出到不同的作用域
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不在main函数的末尾指向cc?
发布于 2020-01-29 11:04:17
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);
}或
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);
}https://stackoverflow.com/questions/59959940
复制相似问题