The Blocks C extension and GIO asynchronous calls

So, I intended to be completely away from my computer during my vacations, but hey. I have been interested in this new extension Apple added to the C language a little while ago which introduces the equivalent of closures to C. Today I spent a few minutes looking into it and writing a few tests with the help of clang.

Here’s something I came up with, to use a block as the callback for a GIO asynchronous call:

[sourcecode language=”cpp”]
#include <Block.h>
#include <gio/gio.h>

typedef void (^Block)();

static void async_result_cb(GObject* source,
GAsyncResult* res,
gpointer data)
Block block = (Block)data;

int main(int argc, char** argv)

if (argc != 2) {
return 1;

GMainLoop* loop = g_main_loop_new(NULL, TRUE);
GFile* file = g_file_new_for_path(argv[1]);

NULL, async_result_cb, (gpointer) ^ (GAsyncResult* res) {
GError* error = NULL;
GFileInfo* info = g_file_query_info_finish(file, res, &error);

if (error) {
g_error("Failed: %s", error->message);

g_message("Content Type: %s",
g_file_info_get_attribute_string(info, G_FILE_ATTRIBUTE_STANDARD_CONTENT_TYPE));



return 0;

Pretty neat, don’t you think? To build you need to use clang and have the blocks runtime installed (libblocksruntime-dev in Debian). Here’s the command I use:

$ clang -fblocks -o gio gio.c -lBlocksRuntime `pkg-config --cflags --libs gio-2.0`

4 Replies to “The Blocks C extension and GIO asynchronous calls”

  1. Neat indeed! IMHOk the code will be a lot more readable if you assigned the inline function to a variable and then passed that as the data.

  2. well given that we are talking about gobject code, it is not that ugly as introduces only new keyword for the blocks pointer. (^)
    But simply looking at the code it looks like some intermediate compiler language to me and not like something a human should be able to read.
    Therefore I think one should just use Vala which has closures build in already.

    As for a readablity, I think Ceylon got the whole higher order functions with C syntax thing best so far:

Leave a Reply to Pavel Cancel reply

Your email address will not be published. Required fields are marked *