[英]passing multiple arguments to a gtk callback function
I'm trying to pass multiple arguments to a gtk call back function I have the following code so far: 我试图将多个参数传递给gtk回调函数,到目前为止我有以下代码:
void add_new_set(GtkDialog *dialog, gint response_id, gpointer callback_params)
{
g_print (gtk_entry_get_text (((struct data *) callback_params)->entry));
}
struct data callback_params;
callback_params.entry = gtk_entry_new();
gtk_container_add(GTK_CONTAINER(content_area), callback_params.entry);
g_signal_connect(dialog,"response",G_CALLBACK (add_new_set),&callback_params);
nothing get g_print ed I get teh following error instead: (tat:5918): Gtk-CRITICAL **: IA__gtk_entry_get_text: assertion 'GTK_IS_ENTRY (entry)' failed 什么也没有得到g_print ed我得到以下错误:(tat:5918):Gtk-CRITICAL **:IA__gtk_entry_get_text:断言'GTK_IS_ENTRY(entry)'失败
(tat:5918): GLib-CRITICAL **: g_print: assertion 'format != NULL' failed (tat:5918):GLib-CRITICAL **:g_print:断言'format!= NULL'失败
I'm open to using techniques other than passing a struct pointer 我愿意使用除传递结构指针以外的技术
thanks 谢谢
You practically need to pack the composite data in a heap-allocated struct
, and pass the pointer to the callback. 实际上,您实际上需要将复合数据打包在分配给堆的
struct
,并将指针传递给回调。
struct data *cb_data = g_new0(struct data, 1);
cb_data->entry = gtk_entry_new();
cb_data->foo = "somefoo";
g_signal_connect(dialog,"response",G_CALLBACK (add_new_set), cb_data);
But you might instead have a single static
variable of some struct
type, and pass the address of that variable to your callback. 但是,您可能会只具有某个
struct
类型的单个static
变量,然后将该变量的地址传递给您的回调。 This is usually bad practice and I don't recommend coding like this (since you want a callback to be somehow reentrant ). 这通常是不好的做法,我不建议这样编码(因为您希望回调以某种方式重新进入 )。
You cannot take the address of a local variable and pass it to g_signal_connect
(because GTK signal handling will use that pointer long after you have returned from your function so popped its call frame ). 您不能使用局部变量的地址并将其传递给
g_signal_connect
(因为从函数返回后很长时间,GTK信号处理将使用该指针,因此会弹出其调用框架 )。
Of course, the issue is when should your program free that cb_data
. 当然,问题是您的程序何时应释放
cb_data
。 Perhaps consider g_signal_connect_data which has a destroy_data
closure notification. 也许考虑g_signal_connect_data ,它具有
destroy_data
关闭通知。 Or connect another signal to free that data (perhaps widget "destroy" or dialog "close" on your dialog
....). 或连接其他信号来释放数据(可能是小部件“破坏”或对话框中的“关闭”您的
dialog
....)。
You should consider using valgrind to debug memory leaks . 您应该考虑使用valgrind调试内存泄漏 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.