我有一个来自here的示例,它在“Increase-Decrease”标题下显示了这一点。
#include <gtk/gtk.h>
gint count = 0;
char buf[5];
void increase(GtkWidget *widget, gpointer label)
{
count++;
sprintf(buf, "%d", count);
gtk_label_set_text(label, buf);
}
void decrease(GtkWidget *widget, gpointer label)
{
count--;
sprintf(buf, "%d", count);
gtk_label_set_text(label, buf);
}
int main(int argc, char** argv) {
GtkWidget *label;
GtkWidget *window;
GtkWidget *frame;
GtkWidget *plus;
GtkWidget *minus;
gtk_init(&argc, &argv);
window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
gtk_window_set_position(GTK_WINDOW(window), GTK_WIN_POS_CENTER);
gtk_window_set_default_size(GTK_WINDOW(window), 250, 180);
gtk_window_set_title(GTK_WINDOW(window), "+-");
frame = gtk_fixed_new();
gtk_container_add(GTK_CONTAINER(window), frame);
plus = gtk_button_new_with_label("+");
gtk_widget_set_size_request(plus, 80, 35);
gtk_fixed_put(GTK_FIXED(frame), plus, 50, 20);
minus = gtk_button_new_with_label("-");
gtk_widget_set_size_request(minus, 80, 35);
gtk_fixed_put(GTK_FIXED(frame), minus, 50, 80);
label = gtk_label_new("0");
gtk_fixed_put(GTK_FIXED(frame), label, 190, 58);
gtk_widget_show_all(window);
g_signal_connect(window, "destroy",
G_CALLBACK (gtk_main_quit), NULL);
g_signal_connect(plus, "clicked",
G_CALLBACK(increase), label);
g_signal_connect(minus, "clicked",
G_CALLBACK(decrease), label);
gtk_main();
return 0;
}
我想知道的是,
g_signal_connect(plus, "clicked",G_CALLBACK(increase), label);
函数将“label”发送给increase函数,它的参数是void increase(GtkWidget *widget, gpointer label)
。现在在increase函数中,gtk_label_set_text()
函数需要一个数据类型GtkLabel
作为它的第一个参数,但是我只看到一个GtkWidget
变量和一个void指针label
作为increase函数的参数。如果是这样,gtk_label_set_text()如何工作?. 最佳答案
在C(而不是C++)中,可以隐式地将void*
转换为指向任何其他类型的指针。这在使用malloc
分配内存时非常常见,它返回一个void*
:
int *myIntArray = malloc(10 * sizeof(int)); // allocate array of 10 ints
您的代码也在做同样的事情,只是传递了参数:
void gtk_label_set_text(GtkLabel *label, const char *text);
void *label = ...;
gtk_label_set_text(label, "some string"); // label is implicitly cast from
// void* to GtkLabel*
关于c - Gtk +回调功能和信号帮助,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/4357462/