为了测试我对Gtk其他位的理解,我想编写一个程序,它总是有一个事件准备好主循环使用。我写了这个简短的程序来尝试这样做:
#include <gtk/gtk.h>
static void toggle(GtkWidget *check, gpointer data)
{
gboolean checked;
g_object_get(check, "active", &checked, NULL);
g_object_set(check, "active", !checked, NULL);
}
int main(int argc, char *argv[])
{
GtkWidget *window, *check;
gtk_init(&argc, &argv);
window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
check = gtk_check_button_new();
g_signal_connect(check, "toggled", G_CALLBACK(toggle), NULL);
gtk_container_add(GTK_CONTAINER(window), check);
gtk_widget_show_all(window);
gtk_main();
}
当我运行此程序并单击复选框时,会出现段错误。是什么赋予了?保持主循环忙的正确方法是什么?
(旁注:它在segfaulting之前可靠地切换2048次 - 一个可疑的圆数。)
答案 0 :(得分:7)
在toggle
处理程序中,您正在设置checked
,这会导致发出toggle
信号,从而重新调用处理程序...
#11564 0xb775ba50 in g_closure_invoke () from /usr/lib/libgobject-2.0.so.0
#11565 0xb776e5d0 in ?? () from /usr/lib/libgobject-2.0.so.0
#11566 0xb77774d6 in g_signal_emit_valist () from /usr/lib/libgobject-2.0.so.0
#11567 0xb7777682 in g_signal_emit () from /usr/lib/libgobject-2.0.so.0
#11568 0xb7e067ba in gtk_toggle_button_toggled ()
我没有完全关注,但我可以看到&11000帧将如何导致段错误。
回答你的另一个问题:我认为保持主循环已满的方法是g_idle_add()
调用:
#include <gtk/gtk.h>
static void toggle(GtkWidget *check, gpointer data)
{
g_print(".");
}
GtkWidget *window, *check;
static gboolean
toggle_it()
{
gboolean checked;
g_object_get(check, "active", &checked, NULL);
g_object_set(check, "active", !checked, NULL);
return TRUE;
}
int main(int argc, char *argv[])
{
gtk_init(&argc, &argv);
window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
check = gtk_check_button_new();
g_signal_connect(check, "toggled", G_CALLBACK(toggle), NULL);
gtk_container_add(GTK_CONTAINER(window), check);
gtk_widget_show_all(window);
g_idle_add((GSourceFunc)toggle_it, NULL);
gtk_main();
}