Search code examples
c++vala

Vala GUI and logic in C++


I have a drawing program that uses SDL, written in C++. I would like to create a graphical interface only in Vala and use it to call functions from a program (functions are ready to use and I only want to call them from the GUI). I was looking for solutions as VAPI, and I was thinking of using GObject, but I can not embrace both. Has anyone done similar things and can you suggest me a solution to my problem?


Solution

  • If you want to use the C++ code in Vala we prepare them properly. Here's an example.

    First you have to tell the valac compiler that the function is defined somewhere else. Let's use the extern directive.

    // ccodetest.vala
    extern void cpp_test_function ();
    
    void main () {
        stdout.printf ("This is Vala code\n");
        cpp_test_function ();
    }
    

    Then the functions in C++ are properly linked with the object files derived from C, we declare them as extern "C".

    // cpplibrary.cpp
    # include
    
    using namespace std;
    
    extern "C" void cpp_test_function () {
        cout << "This is a C + + code\n";
    }
    

    When we are so ready, we can compile Vala code to C. We get ccodetest.c.

    valac -C ccodetest.vala

    Now we can use gcc to compile the object file. We get ccodetest.o.

    gcc-o ccodetest.o ccodetest.c-c-I /usr/include/glib-2.0/ -I /usr/include/glib-2.0/glib/ -I /usr/lib/glib-2.0/include/

    File C++ compile as follows.

    g++ -o cpplibrary.cpp.o cpplibrary.cpp -c

    At the end we linking both files.

    g++ -o ccode_test ccodetest.o cpplibrary.cpp.o -L /usr/lib/ -lglib-2.0 -lgobject-2.0

    The program works as follows:

    $ ./ccode_test
    This is Vala code
    This is a C++ code