[Vala] How to create bindings from arbitrary C code which does not use GObject ?



The binding tutorial (http://live.gnome.org/Vala/Bindings) says:

Vala is designed to allow access to existing C libraries, especially
GObject-based libraries, without the need for runtime bindings....

and further:

The binding generation requires several steps:

   - generating GObject Introspection GIR file (or a GI file made with
   vala-gen-introspect)
   - generation the VAPI binding from the GIR (or GI) file with vapigen
   - tweaking the binding generation with metadata and custom code


But it does not seem to give any explanation on how to create a binding
between  Vala code a C source code which is not based on GObject.


In other  words, for arbitrary C code there must be another way than:

vala-gen-introspect -> Gir -> vapigen -> vapi.

I guess that for arbitrary C code, one has to create the vapi files
manually, but I have not seen that documented anywhere.


Of course there is aslways  the trivial solution hereunder, but it mixes
the logic of C and Vala in the Vala Code.

//=============================================================

serge2 serge2-Macmini:~/development/workspace/vala_test_1/vapi_test$ cat
Makefile

all : hello

hello : _hello.c hello.vala
    valac -o hello --save-temps _hello.c hello.vala

//============================================================

serge2 serge2-Macmini:~/development/workspace/vala_test_1/vapi_test$ cat
_hello.c

#include <stdlib.h>
#include <string.h>

char * A[3];

char** hello(){

    char * a = malloc(sizeof(char)*strlen("hello_a")+1);
    char * b = malloc(sizeof(char)*strlen("hello_b")+1);
    char * c = malloc(sizeof(char)*strlen("hello_c")+1);

    strcpy(a, "hello_a");
    strcpy(b, "hello_b");
    strcpy(c, "hello_c");


    A[0] = a;
    A[1] = b;
    A[2] = c;

    return A;
}

//====================================================================

serge2 serge2-Macmini:~/development/workspace/vala_test_1/vapi_test$ cat
hello.vala

extern char*[] hello();
char* s[3];

void main(string[] arg) {
    //char* s = hello();
    //string s = (string)hello();
    s =  hello();
    print("s = %s\n", (string)s[0]);
    g_free(s[0]);
    g_free(s[1]);
    g_free(s[2]);
}


//===================================================================


The advantage of that solution is that one can call C functions directly
from Vala.

The problem however is that the memory associated with the variables
returned by the C source is not reference counted (it is not Vala, it is C)
and consequently it has to be freed manually, otherwise there is a memory
leak.

Serge.


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