Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 537
Alex Avatar asked Mar 09 '26 01:03

Alex


2 Answers

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 vectors or lists use the indexing interface, which can be viewed here.

like image 156
Constantinius Avatar answered Mar 11 '26 15:03

Constantinius


Take a look at Boost.Python's indexing suite.

like image 34
wilx Avatar answered Mar 11 '26 13:03

wilx



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!