I'm writing an extension module for Python in C++ and I am using boost.python. I want to expose a function that returns a vector<MyClass>
. I'm not exactly sure how to do this and how it will interact with Python WRT memory management.
My first thought was to wrap MyClass
in shared_ptr
, thus the function would return vector<shared_ptr<MyClass>>
. Would this help? What happens when shared_ptr<MyClass>
instances get to Python land? Will they ever be freed?
So my question is: how can I expose a function that returns a vector
of MyClass
instances to Python without leaking memory?
Thanks.
If you use vector<MyClass>
those instances in the vector
are obviously (kind of, since the vector internally uses dynamically allocated memory) stack allocated. It would be different to vector<MyClass*>
which is essentially a vector of dynamically allocated MyClass
instances. In this case, a vector<shared_ptr<MyClass> >
is the better solution.
Boost Python and smart pointers work well together, which can be seen in this example.
To expose vector
s or list
s use the indexing interface, which can be viewed here.