Zah
Zah

Reputation: 6804

Automatic memory management when passing an element of a vector in SWIG

I would like to wrap the constructor for the object Foo, which takes a vector of pointers to Bar:

    Foo(std::vector<Bar*> const&); //!< Constructor

In my interface file I have:

%include "std_vector.i" 
%template (vector_bar_p) std::vector<Bar*>;
%include "foo.h"

In such a way that from Python I can coreate a Foo like:

bar1, bar2 = Bar(), Bar()
foo = Foo([bar1,bar2]) 

The problem is that when bar1 and bar2 are garbage collected, the underlying C++ memory is also deleted, and th methods in foo result in a segmentation fault. I can solve it with:

bar1.thisown = 0
bar2.thisown = 0

But I would like a way of setting the thisown flag automatically when calling the constrctor of Foo, ideally via a typemap in the interface file.

Upvotes: 0

Views: 225

Answers (1)

Alexander Solovets
Alexander Solovets

Reputation: 2507

This is not possible. From SWIG 3.0 documentation:

Given the tricky nature of C++ memory management, it is impossible for proxy classes to automatically handle every possible memory management problem. However, proxies do provide a mechanism for manual control that can be used (if necessary) to address some of the more tricky memory management problems.

Also operating with a raw pointer seem suspicious these days. I'd suggest to use either std::vector<std::shared_ptr<Bar>> or vector<Bar> provided with a valid copy-constructor of Bar.

Upvotes: 1

Related Questions