简体   繁体   中英

boost.python expose function that returns vector<MyClass>

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.

I ran into more-less the same problem: I had to have a module written in C++ returning a vector of custom objects.

While (as mentioned above) Boost.Python indexing suite worked fine and made me like Boost.Python even more, I ended up refactoring the stuff, so that was returning a boost::python::list of my objects instead. This made the invocation code in Python cleaner.

With regards to freeing the memory, besides the indexing suite, also have a look at manage_new_object return value policy:

... wrap C++ functions which return a pointer to an object allocated with a new-expression, and expect the caller to take responsibility for deleting that object...

I use this and it works fairly well.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM