Hanlon
Hanlon

Reputation: 442

Callback function for "delete-event" signal passes incorrect values of variables

Whenever I pass something to a callback function when "delete-event" is triggered with intention to clean something when the window is quit, values that I send get corrupt.

For example, here is a small program that illustrates this problem:

#include <gtk/gtk.h>

void window_quit(GtkWidget *window, int *v) 
{
        g_print("%d\n", *v);
        gtk_main_quit();
}

void normal_function(int *v) 
{
        g_print("%d\n", *v);
}

int main(int argc, char **argv)
{
        gtk_init(&argc, &argv);
        GtkWidget *window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
        gtk_widget_show(window);
        int v = 5;
        normal_function(&v);
        g_signal_connect(window, "delete-event", G_CALLBACK(window_quit), &v);
        gtk_main();
}

How can I call a function on exit and pass it correct values? By the way, I don't have this problem with functions called normally or by other signals.

Upvotes: 1

Views: 1472

Answers (1)

Your signal handler is not of the correct type for "delete-event". The reference manual for GTK3 specified it needs to be:

gboolean
user_function (GtkWidget *widget,
               GdkEvent  *event,
               gpointer   user_data)

Yours is obviously not that. The result is likely a bunch of undefined behavior. The corrupt data you see is likely the punning of GdkEvent as an int. You also don't return any value despite the fact the framework expects your function to return something.

Since G_CALLBACK is a cast, and the framework then casts back to the function pointer type it expects, it's imperative you get in the habit of reading the manual for the signals you connect. There is no type safety here and the compiler can't catch these types of errors.

Upvotes: 2

Related Questions