Menu

#1377 %shared_ptr not working with full namespace

None
open
nobody
5
2023-11-19
2014-07-22
Gedi Zheng
No

%shared_ptr(namespace::class) works, but %shared_ptr(::namespace::class) doesn't work.

A simple example:

example.i:

%module example
%include <std_shared_ptr.i>
%shared_ptr(::ns::Class)
%inline %{
#include <memory>
namespace ns {
class Class {
public:
    Class() : num(0) {}
    int get_num() const { return num; }
private:
    int num;
};
} // namespace ns
std::shared_ptr<::ns::Class> new_class() {
    return std::shared_ptr<::ns::Class>(new ::ns::Class());
}
%}

test.py:

import example
ins = example.new_class()
print ins.get_num()

The above code only works correctly when I replace "%shared_ptr(::ns::Class)" by "%shared_ptr (ns::Class)".

Discussion

  • Olly Betts

    Olly Betts - 2022-03-16

    With currently SWIG git master, the example as written (tweaked for Python3 by adding parentheses to the print) gives:

    Traceback (most recent call last):
      File "/home/olly/git/swig/sf1377/test.py", line 3, in <module>
        print(ins.get_num())
    AttributeError: 'SwigPyObject' object has no attribute 'get_num'
    swig/python detected a memory leak of type 'std::shared_ptr< ns::Class > *', no destructor found.
    

    If I do: replace "%sharedptr(::ns::Class)" by "%sharedptr (ns::Class)". I get a compilation error instead:

    example_wrap.cxx: In function PyObject* _wrap_new_class(PyObject*, PyObject*):
    example_wrap.cxx:3978:50: error: could not convert result from SwigValueWrapper<std::shared_ptr<ns::Class> > to bool
     3978 |     std::shared_ptr<  ns::Class > *smartresult = result ? new std::shared_ptr<  ns::Class >(result) : 0;
          |                                                  ^~~~~~
          |                                                  |
          |                                                  SwigValueWrapper<std::shared_ptr<ns::Class> >
    

    So things seem to have got worse here!

     
  • Olly Betts

    Olly Betts - 2022-04-07
    • labels: shared_ptr --> shared_ptr, reproduced
    • Group: -->
     
  • Olly Betts

    Olly Betts - 2023-11-19

    Retesting with current git master I spotted a problem with how I was building the shared library - the reproducer still fails as given, but s/::ns/ns/g makes it work. So my "things seem to have got worse" above is bogus.

     

Log in to post a comment.