valavapi

How to create and use vapi files?


I want to make a custom vapi file, I have the basic stuff but I obviously miss something and I can't find anywhere how to do this properly. My main goal is to create a torrent app, using libtorrent, and create the GUI (the frontend?) with vala and gtk.

I have a c_func_head.h:

#ifndef WHATEVER_H_INCLUDED
#define WHATEVER_H_INCLUDED
int add(int a, int b);
#endif

c_functions.c:

#include <stdio.h>
#include <stdlib.h>
#include "c_func_head.h"

int add(int a, int b){
  printf("Adding numbers in c...\n");
  return a+b;
}

vala_p.vapi:

[CCode (cheader_filename = "c_func_head.h")]
namespace MyFunc {
    [CCode (cname = "add")]
    public int add (int a, int b);
}

and finally vala_program.vala:

//extern int add(int a, int b);
using MyFunc;

void main(){
    stdout.printf("Calling a c function...\n");
    //stdout.printf("The sum is: %d\n", add2number(2, 2));
    int sum = add(2, 2);
    stdout.printf("The sum is: %d\n", sum);
}

As you can see I used an extern too, it worked with it but I want to use vapi files.

I compiled with (everything is in the same folder):

valac vala_program.vala --vapidir=vala_p.vapi -o mustrun

and the error is:

The namespace name `MyFunc' could not be found using MyFunc;

One more thing. Is it possible to make bindings for libtorrent? It uses C++ and I guess I have to use C++ too.


Solution

  • You can't make Vala bindings of C++ code. Only C. There a a guide to writing legacy bindings and a binding for Transmission, which is C-based.

    As for the specific error you have, you want to call valac vala_program.vala vala_p.vapi if the library (i.e., header files) are the the same directory or valac vala_program.vala --pkg vala_p --vapidir=/path/to/directory/containing/vapi.