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 thevectorare obviously (kind of, since the vector internally uses dynamically allocated memory) stack allocated. It would be different tovector<MyClass*>which is essentially a vector of dynamically allocatedMyClassinstances. In this case, avector<shared_ptr<MyClass> >is the better solution.Boost Python and smart pointers work well together, which can be seen in this example.
To expose
vectors orlists use the indexing interface, which can be viewed here.