【问题标题】:Pass received argument to a callback function将接收到的参数传递给回调函数
【发布时间】: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


【解决方案1】:

您的代码中的问题是:-

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

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

void
user_function (GtkButton *button,
               gpointer   user_data)

你的回调函数中缺少一个参数

【讨论】:

  • ???????哦。我的。善良。非常感谢你
【解决方案2】:

你有两个问题:

首先,你传递的是一个局部变量的地址,但是函数返回后就不能使用了。

其次,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); 以防止内存泄漏。

【讨论】:

  • 您好,感谢您抽出宝贵时间回答,我尝试了您的解决方案,但它仍然向我显示一堆随机数字,我对 function2 使用以下内容是否正确:function2(void* nb) {...?谢谢!
  • 也许你应该使用GINT_TO_POINTER
  • 哦,我不知道我要去试试谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-03-28
  • 2011-10-05
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多