boost.python expose function that returns vector<MyClass>

只谈情不闲聊 提交于 2019-12-22 10:56:32

问题


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.


回答1:


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.




回答2:


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




回答3:


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.



来源:https://stackoverflow.com/questions/7268496/boost-python-expose-function-that-returns-vectormyclass

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!