JavaFX Tutorials

Saturday, August 27, 2016

GTK Macro to Reduce Boilerplate Callback Code

When working with GTK, you tie callbacks to signals.  For example, you might have an app_exit() function that you want to be invoked when a window's delete event is posted.  To do this, you'll write the callback and use g_signal_connect() make the event/function association.

If your callback is an existing GTK function, you can use the GObject macro g_signal_connect_swapped() to reduce the boilerplate.

A function destroy() is registered to a GtkWidget "window" with the event "delete".

g_signal_connect( G_OBJECT(window), "destroy", G_CALLBACK(destroy), NULL);

In this case, destroy() simply delegates to an existing function.

void
destroy(GtkWidget* widget, gpointer user_data) {
    gtk_main_quit();
}

Depending on where you are in your program, you may also need a forward declaration.

void destroy(GtkWidget*, gpointer);

This can be reduced to a single macro invocation using g_signal_connect_swapped().  The g_signal_connect() call, the boilerplate callback, and the forward declaration are replaced with the following.

g_signal_connect_swapped( G_OBJECT(window), "destroy", G_CALLBACK(gtk_main_quit), NULL);


No comments:

Post a Comment