【发布时间】:2020-04-15 19:44:25
【问题描述】:
我正在用 C 编写一个 Gtk 项目。
我从 main.c 调用一个 function1,并以 int 地址作为参数。
在那个 function1 中,我可以访问第一个值,但是在那个 function1 的末尾(内部),我调用了另一个 function2(这是一个点击事件的回调函数)并将我从 function1 参数中得到的地址传递给它。
但是在function2中,地址变了,肯定想不通为什么...
我的项目是这样的:
[main.c]
int main(...) {
int a = 50;
function1(&a);
}
[function1.c]
void function1(int* nb) {
...
g_signal_connect(G_OBJECT(button),"clicked", G_CALLBACK(function2), &nb);
// I know that the 4th arg expects void*, but even though I give the address of that _nb_ parameter, still can't get that 50 in function2
}
[function2.c]
void function2(void* nb) {
...
printf("should got 50 : %d ", *(int*)nb);
// shows random 8 digits number like 60035152
}
编辑:忘了提到每个函数都在一个单独的文件中,我不知道这是否重要,只要我执行包含并给出原型......
提前谢谢你...
【问题讨论】:
-
传入
nb而不是&nb。 -
您正在传递一个局部变量的地址。当函数返回时,该地址变得无效。
-
所以在function1中,在g_signal_connect中,我通过了nb,但它仍然没有给我function2中的50
标签: c function callback arguments gtk