cimportvala

Not able to call C functions from Vala


I am trying to use this C statistics library in Vala. The C file with all statistical functions are in statlib.c.

I used method given in a simple example given here.

My code is in main.vala, which is as follows:

extern double sum(double[] doublelist, int len); 

public static void main(string[] args){
    var numlist = {1.1,2.2,3.3,4.4,5.5};
    var total = sum(numlist, numlist.length); 
    stdout.printf("The sum is %d \n", total);
}

However, it is producing following error:

$ vala main.vala statlib.c 
statlib.c:2.2-2.9: error: syntax error, invalid preprocessing directive
statlib.c:2.10-2.10: error: syntax error, expected identifier
statlib.c:3.2-3.9: error: syntax error, invalid preprocessing directive
statlib.c:4.2-4.9: error: syntax error, invalid preprocessing directive
statlib.c:5.2-5.9: error: syntax error, invalid preprocessing directive
statlib.c:6.2-6.9: error: syntax error, invalid preprocessing directive
statlib.c:634.39-634.39: error: syntax error, unexpected character
statlib.c:635.45-635.45: error: syntax error, unexpected character
statlib.c:1325.13-1325.17: error: syntax error, expected declaration
statlib.c:1325.28-1325.32: error: syntax error, expected declaration

Lines 2-6 in statlib.c are of include files:

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <float.h>
#include "statlib.h"

Lines 634-636 are:

r = (sumxy - (sumx * sumy) / n) / \
    (sqrt((sumxsqr - (sumx * sumx) / n) \
    * (sumysqr - (sumy * sumy) / n)));

Line 1325 in c file is a function declaration:

int compare(const void* a, const void* b)

Where is the problem and how can I use this C library functions in Vala?


Solution

  • You are trying to compile your C code with vala here:

    $ vala main.vala statlib.c 
    

    That does not work. You have to compile the C library with a C compiler (like clang or gcc), the Vala code with the Vala compiler and finally link both together with a linker.

    The easiest way to do this would be something like the meson build system which will automate a lot of the steps for you.

    The meson.build file could look something like this:

    project('foo', 'c', 'vala')
    
    bar_lib = library('bar', 'statlib.c')
    bar_dep = declare_dependency(link_with: bar_lib, 
                               include_directories: include_directories('.'))
    
    executable('foo', 'foo.vala', dependencies: [bar_dep])
    

    Build with:

    meson build
    ninja -C build
    

    To actually use the C code in Vala you also have to write or generate a bar.vapi file.

    More info: