Search code examples
introspectiontypelibvala

How to generate GIR files from the Vala compiler?


I am trying to create python bindings to a vala library using pygi with gobject introspection. However, I am having trouble generating the GIR files (that I am planning to compile to typelib files subsequently). According to the documentation valac should support generating GIR files.

Compiling the following

helloworld.vala

public struct Point {
    public double x;
    public double y;
}

public class Person {

    public int age = 32;

    public Person(int age) {
        this.age = age;
    }

}

public int main() {

    var p = Point() { x=0.0, y=0.1 }; 
    stdout.printf("%f %f\n", p.x, p.y);

    var per = new Person(22);
    stdout.printf("%d\n", per.age);

    return 0;

}

with the command

valac helloworld.vala --gir=Hello-1.0.gir

doesn't create the Hello-1.0.gir file as one would expect. How can I generate the gir file?


Solution

  • To generate the GIR one has to put the functions to be exported under the same namespace

    hello.vala

    namespace Hello {
        public struct Point {
            public double x;
            public double y;
        }
    
        public class Person {
    
            public int age = 32;
    
            public Person(int age) {
                this.age = age;
            }
        }
    }
    
    public int main() {
    
        var p = Hello.Point() { x=0.0, y=0.1 }; 
        stdout.printf("%f %f\n", p.x, p.y);
    
        var per = new Hello.Person(22);
        stdout.printf("%d\n", per.age);
    
        return 0;
    
    }
    

    and then run the following command.

    valac hello.vala --gir=Hello-1.0.gir --library Hello-1.0
    

    This will generate a gir and a vapi file in the current directory.

    Then to generate the typelib file, one needs to run

    g-ir-compiler --shared-library=hello Hello-1.0.gir -o Hello-1.0.typelib
    

    assuming the shared library has been compiled to libhello.so