I'm trying to pass an integer using g_signal_connect into my function to display the button index but it throws an error:
gui.c:35:39: warning: cast to pointer from integer of different size [-Wint-to-pointer-cast]
G_CALLBACK(button_clicked), (gpointer)row+column);
^
/usr/include/glib-2.0/gobject/gsignal.h:475:73: note: in definition of macro ‘g_signal_connect’
g_signal_connect_data ((instance), (detailed_signal), (c_handler), (data), NULL, (GConnectFlags) 0)
^~~~
Here's my code:
#include <gtk/gtk.h>
void button_clicked(GtkWidget *widget, gpointer data) {
g_print("Button %p clicked\n", data);
gtk_button_set_label (GTK_BUTTON (widget), "X");
}
#include <gtk/gtk.h>
int main(int argc, char *argv[]) {
GtkWidget *window;
GtkWidget *fixed;
gchar *values[9] = {"1","2","3","4","5","6","7","8","9"};
GtkWidget *button[9];
gtk_init(&argc, &argv);
window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
gtk_window_set_title(GTK_WINDOW(window), "GtkFixed");
gtk_window_set_default_size(GTK_WINDOW(window), 300, 200);
gtk_window_set_position(GTK_WINDOW(window), GTK_WIN_POS_CENTER);
fixed = gtk_fixed_new();
gtk_container_add(GTK_CONTAINER(window), fixed);
for (int row = 0; row < 9; row+=3){
for (int column = 0; column < 3; column++){
button[row+column] = gtk_button_new_with_label(values[row+column]);
gtk_fixed_put(GTK_FIXED(fixed), button[row+column], column*70, row*30);
gtk_widget_set_size_request(button[row+column], 50, 50);
g_signal_connect(G_OBJECT(button[row+column]), "clicked",
G_CALLBACK(button_clicked), (gpointer)row+column);
}
}
g_signal_connect(G_OBJECT(window), "destroy",
G_CALLBACK(gtk_main_quit), NULL);
gtk_widget_show_all(window);
gtk_main();
return 0;
}
I've tried using gint instead of int for row and column but that doesn't seem to change anything. What am I doing wrong?
First of all, the expression (gpointer)row+column
is equal to ((gpointer)row)+column
, which is equal to &((gpointer)row)[column]
. This is probably not what you expect.
Secondly, the compiler most likely not be able to see that neither row
nor column
will never be negative. This could lead to it generating bad code. Use unsigned
as the type for row
and column
instead.
And finally for "fixing" your warning: int
is typically 32 bits, while it seems that pointers on your system is larger than that (probably 64 if you're on a 64-bit system). You need to temporarily convert to a type that is compatible with both integers and pointers.
Putting all together the expression should look something like
(gpointer)(uintptr_t)(row+column)
Then in the callback you need to do the opposite casting:
unsigned row_col = (unsigned)(uintptr_t)data;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.