将收到的参数传递给回调函数
Pass received argument to a callback function
我正在用 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
}
编辑:忘了说每个函数都在一个单独的文件中,我不知道这是否重要,只要我包含并提供原型...
提前谢谢你...
你有两个问题:
首先,您传递的是局部变量的地址,但不能在函数后使用 returns。
其次,function2
期望 nb
是指向 int
的指针,但您将指向 int
的指针传递给 g_signal_connect()
.
void function1(int* nb) {
...
int *nb_copy = malloc(sizeof(int));
*nb_copy = *nb;
g_signal_connect(G_OBJECT(button),"clicked", G_CALLBACK(function2), nb_copy);
// 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
}
function_2()
应该 free(nb);
用完它以防止内存泄漏。
您的代码中的问题是:-
1) 您正在将变量的地址传递给回调函数
所以不是&nb,它应该是nb。
2)点击信号的回调函数(https://developer.gnome.org/gtk3/stable/GtkButton.html#GtkButton-clicked_
void
user_function (GtkButton *button,
gpointer user_data)
您的回调函数中缺少参数
我正在用 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
}
编辑:忘了说每个函数都在一个单独的文件中,我不知道这是否重要,只要我包含并提供原型...
提前谢谢你...
你有两个问题:
首先,您传递的是局部变量的地址,但不能在函数后使用 returns。
其次,function2
期望 nb
是指向 int
的指针,但您将指向 int
的指针传递给 g_signal_connect()
.
void function1(int* nb) {
...
int *nb_copy = malloc(sizeof(int));
*nb_copy = *nb;
g_signal_connect(G_OBJECT(button),"clicked", G_CALLBACK(function2), nb_copy);
// 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
}
function_2()
应该 free(nb);
用完它以防止内存泄漏。
您的代码中的问题是:-
1) 您正在将变量的地址传递给回调函数 所以不是&nb,它应该是nb。
2)点击信号的回调函数(https://developer.gnome.org/gtk3/stable/GtkButton.html#GtkButton-clicked_
void
user_function (GtkButton *button,
gpointer user_data)
您的回调函数中缺少参数