Search code examples
lambdadelegatesvala

How to cast lambda in Vala


Keep receiving compile-time warring from cc (not valac). Tried to cast the lambda, but don't know how to. I'm new to Vala. Hope someone can help. Thanks a lot. The following code is an example where cc will complain about the incorrect type of the lambda, the argument of the method foreach. The Vala I'm using is version 0.36.1 and cc is version 4.9.2.

public static int main(string[] args)
{
    var hash = new GLib.HashTable<string, string>(GLib.str_hash, GLib.str_equal);
    hash.insert("one", "apple");
    hash.insert("two", "banana");
    hash.insert("three", "cherry");
    hash.foreach((key, val)=>stdout.printf("%s => %s\n", key, val));
    return 0;
}

Solution

  • You can safely ignore warnings from your C compiler as long as

    1. You are not writing VAPI bindings yourself. You should then make sure there are as few C warnings as possible.

    2. They are not errors, but then you would not be able to create a binary anyway.

    I usually pass "-X -w" to the vala compiler to suppress C warnings.

    Let us look at your concrete example anyway, I get this warning (GCC 6.3.0 on MSYS2 64-Bit Windows):

    d:/msys64/home/Admin/hash-test.vala.c: In function '_vala_main':
    d:/msys64/home/Admin/hash-test.vala.c:69:30: warning: passing argument 2 of 'g_hash_table_foreach' from incompatible pointer type [-Wincompatible-pointer-types]
      g_hash_table_foreach (hash, ___lambda4__gh_func, NULL);
                                  ^~~~~~~~~~~~~~~~~~~
    In file included from D:/msys64/mingw64/include/glib-2.0/glib.h:50:0,
                     from d:/msys64/home/Admin/hash-test.vala.c:5:
    D:/msys64/mingw64/include/glib-2.0/glib/ghash.h:99:13: note: expected 'GHFunc {aka void (*)(void *, void *, void *)}' but argument is of type 'void (*)(const void *, const void *, void *)'
     void        g_hash_table_foreach           (GHashTable     *hash_table,
                 ^~~~~~~~~~~~~~~~~~~~
    

    The important bit is this one (I have aligned it for better comparison):

    expected    'GHFunc {aka void (*)(      void *,       void *, void *)}'
    but argument is of type 'void (*)(const void *, const void *, void *)'
    

    So it is a classic const correctnes warning.

    The lambda has two const arguments, but the function pointer type (GHFunc) of g_hash_table_foreach is declared with more permissive non-const pointers.

    That should not be a problem, so you can safely ignore it.