c - 将接收到的参数传递给回调函数

标签 c function callback arguments gtk

我正在用 C 语言开发一个 Gtk 项目。

在 main.c 中,我调用一个 function1,并以 int 地址作为参数。

在该函数1中,我可以访问第一个值,但随后在该函数1的末尾(内部),我调用另一个函数2> (这是点击事件的回调函数)并将我从 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
}

编辑:忘记提及每个函数都在一个单独的文件中,我不知道这是否重要,只要我执行包含并给出原型(prototype)...

提前谢谢您...

最佳答案

您的代码中的问题是:-

1) 您将变量的地址传递给回调函数 所以应该是 nb,而不是 &nb。

2) 这是点击信号的回调函数( https://developer.gnome.org/gtk3/stable/GtkButton.html#GtkButton-clicked_

void
user_function (GtkButton *button,
               gpointer   user_data)

您的回调函数中缺少参数

关于c - 将接收到的参数传递给回调函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59473619/

相关文章:

c - C中VOID()是什么意思

c - 尝试访问二维数组时出现 SIGSEGV 错误

C - 访问结构数组

c - 内存只读的机制是什么?

python - 列表中 x 元素的最后 3 个元素的总和作为新列表 [python 3]

c++ - 为什么尽管我的函数和 cout 语句放置错误,我的程序仍能运行?

python - 名称错误 : name 'ReleaseDeal' is not defined in Django

javascript - Node.js 正确的回调错误句柄

javascript - Electron :X不是函数>>>(使用ipcrenderer/ipcmain进行回调)

javascript - 我怎样才能让这个 JSONP 调用返回一个值?