GTK3 Pass multiple arguments to button callback

I have a GTK3 application in C. I have a regular button

GtkWidget *btn = gtk_button_new_with_label("Button");
g_signal_connect(btn, "clicked", G_CALLBACK(my_function), /* values here */);

and a corresponding callback function:

static void my_function(GtkWidget* widget, gpointer *data){...}

Instead of passing a single argument I would like to pass multiple values. I saw you can somehow do it with a struct but so far I couldn’t do it. Does anyone have some working examples? Thank you!

The only way to do that in C is to pack all the data inside a structure and pass the structure to the callback.

First, you define the structure:

typedef struct {
  char *arg1;
  int arg2;
  GtkWidget *arg3;
} CallbackData;

then you allocate it before connecting to the signal:

CallbackData *data = g_new0 (CallbackData, 1);

data->arg1 = g_strdup ("some string");
data->arg2 = 42;
data->arg3 = some_other_widget;

g_signal_connect (btn, "clicked", G_CALLBACK (my_function), data);

Inside the my_function handler, you take the user data generic pointer and assign it to a structure pointer:

static void
my_function (GtkButton *button,
             gpointer user_data)
{
  CallbackData *data = user_data;

  // use data->arg1, data->arg2, data->arg3 as needed
}

The user_data argument is not a gpointer*: it’s a gpointer. Those are two very different types.

1 Like