[Vala] Calling C code from Vala



Looking inside the vala sources I have seen how valaparser.vala interacts with parser.c.
It's the only place it's used the [Import ()] directive and imho this is a nice feature
that should be documented on the wiki. (feel free to add this example)

Here's an explanation:

$ cat foo.vala 
using GLib;

public class Foo.Bar
{
        public static int main(string[] args)
        {
                hello_msg("World!");
                return 0;
        }

        [Import ()]
        public static void hello_msg(string name);
}

We define an imported static method (no need to be static, but for a simple example is ok)
on the Bar class of the Foo namespace.

Now we implement the hello_msg function in C inside bar.c:

$ cat bar.c 
void foo_bar_hello_msg(void *name)
{
        printf("Name: %s\n", name);
}

That is. Quite easy :)

To build just use this Makefile:

$ valac foo.vala bar.c -o foo

$ ./foo
Hello World!

  --pancake



[Date Prev][Date Next]   [Thread Prev][Thread Next]   [Thread Index] [Date Index] [Author Index]