将收到的参数传递给回调函数 [英] Pass received argument to a callback function
问题描述
我正在用C进行一个Gtk项目.
I am working on a Gtk project in C.
从main.c中,我调用一个以整数地址作为参数的 function1 .
From the main.c I call a function1 with an int address as a parameter.
在该 function1 中,我可以访问该第一个值,但是在该 function1 的末尾(内部),我调用另一个 function2 (这是click事件的回调函数),并将我从 function1 参数获得的地址传递给它.
In that function1, I can access that first value, but then at the end (inside) of that function1, I call another function2 (which is a callback function to a click event) and pass it the address I got from the function1 parameter.
但是在 function2 中,地址已更改,绝对无法弄清为什么 ...
But in function2, the address have changed, definitely can't figure out why...
我的项目如下:
[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
}
忘记提及每个函数在单独的文件中,只要我执行包含并给出原型,我就不知道这是否重要...
Forgot to mention that each function is in a separate file, I don't know if that matters as long as I do the includes and gives the prototypes...
提前谢谢...
推荐答案
您的代码中的问题是:-
The problem's in your code are:-
1)您正在将变量的地址传递给回调函数 所以应该是nb,而不是& nb.
1) you are passing the address of the variable to the callback function so instead of &nb, it should be nb.
2)这是点击信号的回调函数( https://developer.gnome.org/gtk3/stable/GtkButton.html#GtkButton-clicked_
2) this is the callback function for clicked signal (https://developer.gnome.org/gtk3/stable/GtkButton.html#GtkButton-clicked_
void
user_function (GtkButton *button,
gpointer user_data)
您在回调函数中缺少参数
you are missing an argument in your callback function
这篇关于将收到的参数传递给回调函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!