Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using SWIG to create java bindings for C++ classes

With SWIG am able to create simple bindings for my C++ code.

My question here is for multiple inheritance.

Our C++ codebase has a iClass as base class, which acts as interface. Also we have classes that are derived from two classes, one of which is this interface class.

Now my question is can we use SWIG to create bindings for such a codebase, assuming that we can put our class iClass as an Interface in Java.

It is still multiple inheritance but a very specific case of it and is analogous with interface concept of java.

like image 934
Sinay Avatar asked Dec 28 '25 11:12

Sinay


1 Answers

The case with SWIG is that it indeed will only extend the first base class you list (in the code example below that would be I1) and omit the rest. Interestingly, the C++ compiled code WILL include all the base methods, they are just not available to the Java JNI wrapper.

Multiple inheritance is another paradigm than interfacing, making it hard to cast / interpret an Object in Java as belonging to a particular interface.

What you can do though - which does feel a tad fugly - is to add a compiler directive to the header file of the class which is inheriting from multiple classes. Like so:

class Foo : public I1, I2
{
    public:
        Foo();
        ~Foo();

        #ifdef SWIG
        void aI2Method();
        double aI2Property;
        #endif

    protected:
        void bar();
}

When compiling with SWIG, property SWIG is defined. As such the method "aI2Method" and public property "aI2Property" (which for the sake of argument, we assume are defined in base class I2) are used by SWIG and defined in the JNI wrapper for this class "Foo". Just add the public methods / properties in between the conditional directive.

In Java you can then invoke "aI2Method" on Foo or get/set the public "aI2Property"-property, and the native compiled code will invoke these on the I2 base class. Note that this means you don't need to add the same directive including the definitions or function bodies of these methods in the .cpp file of "Foo", as placing it in the header file will suffice. This way, at least the .cpp files remain clean.

like image 155
Igor Zinken Avatar answered Dec 31 '25 02:12

Igor Zinken



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!