Generate SWIG JNI for reference pointer

53 Views Asked by At

I am trying to generate JNI wrappers using SWIG (4.1) for the following C++ code. The Header.h looks like this:

class Butler
{
public:
    Butler();
    ~Butler();

    void setHoursAvailable(int hours);
    void setGreeting(const std::string& greetings);
    int getHours();
    std::string getGreetings();
};

class ButlerService
{
public:
    ButlerService();
    ~ButlerService();

    Butler*& getButler(const int & index);
    void addButler(Butler *& addMe);
    std::vector<Butler*> getAllButlers();
};

As you can see, one of the ButlerService class method returns a reference to pointer, and one of them takes it in. The SWIG interface looks like this.

%include "stl.i"

%nodefaultctor Butler;
%nodefaultdtor Butler;

// Type typemaps for marshalling Butler *&
%typemap(jni) Butler *& "jobject"
%typemap(jtype) Butler *& "Butler"
%typemap(jstype) Butler *& "Butler"

%typemap(javain) Butler *& "$javainput"

%typemap(javaout) Butler *& {
    return $jnicall;
}

%{
#include "Header.h"
%}

%template("ButlerVector") std::vector<Butler*>;

class Butler
{
public:
    Butler();
    Butler(const std::string & message, const int & hours);
    ~Butler();

    void setHoursAvailable(int hours);
    void setGreeting(const std::string & greetings);
    int getHours();
    std::string getGreetings();
};

class ButlerService
{
public:
    ButlerService();
    ~ButlerService();

    Butler*& getButler(const int & index);
    void addButler(Butler *& addMe);
    std::vector<Butler*> getAllButlers();
};

ISSUE: Adding a Butler created in JAVA like this:

ButlerService newButlerService = new ButlerService();
Butler test = new Butler("Hi ho", 6);
newButlerService.addButler(test );

is not created in CPP. And while retrieving, due to memory errors, it crashes. I am suspecting this has to with the way I have defined %typemap(javain). How can I solve this? I could do away with the reference to pointer, but I want to see what will work without doing that. Thanks.

0

There are 0 best solutions below