// gcc 1.c -o 0 $(pkg-config --cflags --libs gtk+-2.0)
#include <gtk/gtk.h>
#include <gdk/gdkkeysyms.h>
struct tst
{
GtkWidget *win, *vb, *ent, *btn, *lbl;
GtkAccelGroup *acc;
GClosure *cls;
};
static void print_val(int nmb)
{
g_printf("%d\n", nmb);
}
static void window_new()
{
struct tst *prg = g_new0(struct tst, 1);
prg->win = gtk_window_new(GTK_WINDOW_TOPLEVEL);
prg->vb = gtk_vbox_new(TRUE, 0);
prg->ent = gtk_entry_new();
prg->btn = gtk_button_new_with_label("Print!");
prg->lbl = gtk_label_new("Enter the string.");
prg->acc = gtk_accel_group_new();
int nmb = 140;
prg->cls = g_cclosure_new(G_CALLBACK(print_val), nmb, NULL);
gtk_container_add(GTK_CONTAINER(prg->win), GTK_WIDGET(prg->vb));
gtk_box_pack_start(GTK_BOX(prg->vb), GTK_WIDGET(prg->ent), FALSE, FALSE, 0);
gtk_box_pack_start(GTK_BOX(prg->vb), GTK_WIDGET(prg->btn), FALSE, FALSE, 0);
gtk_box_pack_start(GTK_BOX(prg->vb), GTK_WIDGET(prg->lbl), FALSE, FALSE, 0);
g_signal_connect(prg->win, "destroy", G_CALLBACK(gtk_main_quit), NULL);
g_signal_connect(prg->btn, "clicked", G_CALLBACK(print_val), (gpointer)nmb);
gtk_window_set_title(GTK_WINDOW(prg->win), "Enter the string");
gtk_window_add_accel_group(GTK_WINDOW(prg->win), prg->acc);
gtk_accel_group_connect(prg->acc, GDK_KEY_P, (GDK_CONTROL_MASK | GDK_SHIFT_MASK), GTK_ACCEL_MASK, prg->cls);
gtk_widget_show_all(GTK_WIDGET(prg->win));
}
int main(int argc, char *argv[])
{
gtk_init(&argc, &argv);
window_new();
gtk_main();
return 0;
}
I want to make this program to print 140 on console every time I pressed the button or Ctrl + Shift + P.
But this program prints the weird value(not 140) when I pressed the button or Ctrl + Shirt + P.
What should I do?
Your print_val
callback needs to have the correct number of parameters. If you look up the GtkButton::clicked
signal in the GTK documentation, you will see it has this signature:
void user_function (GtkButton *button, gpointer user_data)
So the first parameter passed to print_val
when you click the button is the address of the button itself. This is the "weird value" you are printing.
Contrary to Jens' answer here, GLib does provide a portable way to cast an int
to a pointer. So to achieve what you want, you need to connect your signal like this:
g_signal_connect(prg->btn, "clicked", G_CALLBACK(print_val), GINT_TO_POINTER(nmb));
and then make your callback like this:
static void print_val(GtkButton *button, gpointer nmb)
{
g_printf("%d\n", GPOINTER_TO_INT(nmb));
}