tags:

views:

470

answers:

2

Hi there,

I'd like to hack on an existing GLib based C project using vala. Basically what I'm doing is, at the beginning of my build process, using valac to generate .c and .h files from my .vala files and then just compiling the generated files the way I would any .c or .h file. This is probably not the best way, but seems to be working alright for the most part. My problem is that I'm having a hard time accessing my existing C code from my Vala code. Is there an easy way to do this? I've tried writing my own .vapi files (I didn't have any luck with the tool that came with vala), but I can't find any decent documentation on how to write these. Does any exist? Do I need one of these files to call existing C code?

Thanks.

+1  A: 

Yes, to call a C function, you need to write a binding for it. The process is described in http://live.gnome.org/Vala/Tutorial#Binding_Libraries_with_VAPI_Files, however, this doesn't apply directly to custom functions or libraries written without GObject. You'll probably need help from #vala IRC channel if you have complex binding for non-GObject libraries.

However, most of the time, we use simple vapi files to bind some autoconf define or some functions written in plain C, for efficiency reason or broken vala, or whatever other reason. And this is the way that most people do:

myfunc.vapi

[CCode (cheader_filename = "myfunc.h")]
namespace MyFunc {
    [CCode (cname = "my_func_foo")]
    public string foo (int bar, Object? o = null);
}

myfunc.h (and corresponding implementation in a .c linked with your project)

#include <glib-object.h>
char* my_func_foo(int bar, GObject* o)

example.vala could be

using MyFunc;

void main() {
    baz = foo(42);
}

When compiling with valac, use --vapidir= to give the directory location of the myfunc.vapi. Depending on your build system, you may need to pass extra argument to valac or gcc CFLAGS in order to link everything together.

elmarco
Thanks! One problem I'm having is that when I specify the header file in myfunc.vapi, the .c output from valac writes #include <myfunc.h> when what I really want is #include "myfunc.h". Any idea how to solve this? Is it solvable?
Jordan
this shouldn't be a big deal, as long as the file is not installed in your system include, it will be open in your project directory, if you provide the path with -I.. (example: -I$(topsrc_dir)/libfoo)
elmarco