Home > database >  user pointer in g_signal_connect is not passed correctly
user pointer in g_signal_connect is not passed correctly

Time:05-14

I have a gtk scale with range, and my goal is to capture when the user releases the click from the scale. (value-changed is called even when the slider is still changing, that's why it's not useful in my case). so I used this signal. The signal callback is working correctly, it's called when the mouse click is released, the problem is that the user pointer is kinda random. and changes at every call. Here's my code:


static gboolean callback(GtkWidget *widget, GdkEventButton event, gpointer data) {
  int *n = (int *)data;

  printf("Pointer: %p\n", n);
  printf("Value: %d\n", *n);
  return FALSE;
}

static void activate(GtkApplication *app, gpointer user_data) {
  GtkWidget *window;
  GtkWidget *button_box;
  GtkWidget *slider;

  int *n = malloc(sizeof(int));
  *n = 1000;
  printf("Initialized pointer: %p\n", n);

  window = gtk_application_window_new(app);
  gtk_window_set_title(GTK_WINDOW(window), "Window");
  gtk_window_set_default_size(GTK_WINDOW(window), 200, 200);

  button_box = gtk_button_box_new(GTK_ORIENTATION_HORIZONTAL);
  gtk_container_add(GTK_CONTAINER(window), button_box);

  gtk_widget_add_events(window, GDK_BUTTON_RELEASE_MASK);

  slider = gtk_scale_new_with_range(GTK_ORIENTATION_HORIZONTAL, 0, 100, 1);
  g_signal_connect(slider, "button-release-event", G_CALLBACK(callback), n);
  gtk_container_add(GTK_CONTAINER(button_box), slider);

  gtk_widget_show_all(window);
}

The output is:

Initialized pointer: 0x5594c31e5de0
Pointer: 0x5594c30a3e40
Value: 7
Pointer: 0x5594c30a3e40
Value: 7
Pointer: 0x5594c30a3da0
Value: 7
Pointer: 0x5594c30a3b20
Value: 7
Pointer: 0x5594c30a3bc0
Value: 7
Pointer: 0x5594c30a3bc0
Value: 7
Pointer: 0x5594c30a3bc0
Value: 7
Pointer: 0x5594c30a3c60
Value: 7

it's also the same case if I replace n with NULL like this:

g_signal_connect(slider, "button-release-event", G_CALLBACK(callback), NULL);

is still passes random pointers when it should've been (nil)

it doesn't make any sense.

Edit: the only messing function is main, that's the whole code:

int main(int argc, char **argv) {
  GtkApplication *app;
  int status;

  app = gtk_application_new("org.gtk.example", G_APPLICATION_FLAGS_NONE);
  g_signal_connect(app, "activate", G_CALLBACK(activate), NULL);
  status = g_application_run(G_APPLICATION(app), argc, argv);
  g_object_unref(app);

  return status;
}

CodePudding user response:

My main suspect is that GdkEventButton event should have been GdkEventButton *event

It is very rare that you pass full structures as parameters in C (and in Gtk)

  • Related