0

I need to port an existing C++ library to Java. In the C++ code there is a factory method:

std::shared_ptr<Role> createRole(std::string name)

which will return a nullptr if it was not possible to create the Role.

Unfortunately if I try to port this code with SWIG it will fail silently at this point. I guess that is because Java doesn't know about nullptr and SWIG is most likely ignoring it. Is my assumption right? Because I'm originally a Java developer and don't know much about SWIG and C++...

Sadly I can't change the existing C++ code. Is there any workaround for this? Or will I have to write a Wrapper for this special case? This problem occures in 4 or 5 places in the project.

little_planet
  • 1,005
  • 1
  • 16
  • 35

1 Answers1

1

The problem is highly likely in your code. I just checked out the following code with gcc-4.8 and swig-2.0, and it worked perfectly:

test.h

#include <string>
#include <memory>

class Test {
  public:
  std::shared_ptr<std::string> test(bool isNull) {
    return isNull ? nullptr : std::make_shared<std::string>("test");
  }
};

test.i

%module "test"

%include "std_shared_ptr.i"
%include "std_string.i"

%shared_ptr( std::string )

%{
#include "test.h"
%}

%include "test.h"

check.py

import test
t = test.Test()
print t.test(True)
print t.test(False)

The output of python check.py is:

None
<Swig Object of type 'std::shared_ptr< std::string > *' at 0x7f03436501e0>swig/python detected a memory leak of type 'std::shared_ptr< std::string > *', no destructor found.

Alexander Solovets
  • 2,447
  • 15
  • 22