Boost.Python的揭露函数返回矢量&lt;&MyClass的GT; [英] boost.python expose function that returns vector<MyClass>
问题描述
我在写C的扩展模块为Python ++和我使用Boost.Python的。我要揭露一个返回矢量&lt功能; MyClass的&GT;
。我不完全知道如何做到这一点,将如何与Python WRT内存管理进行互动。
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.
我的第一个想法是包裹 MyClass的
在的shared_ptr
,因此该函数将返回矢量&lt;&的shared_ptr LT; MyClass的&GT;&GT;
。这会帮助吗?会发生什么事时,的shared_ptr&LT; MyClass的&GT;
实例获得到Python的土地?他们才会被释放?
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?
所以我的问题是:我怎么可以公开返回 MyClass的
实例的Python 矢量
无功能内存泄露?
So my question is: how can I expose a function that returns a vector
of MyClass
instances to Python without leaking memory?
感谢。
推荐答案
如果您使用矢量&lt; MyClass的&GT;
在载体的那些实例
显然(那种,因为向量在内部使用动态分配的内存)堆栈分配。这将是矢量&lt不同; MyClass的*&GT;
这实质上是动态分配的 MyClass的
实例的载体。在这种情况下,一个矢量&lt;的shared_ptr&下; MyClass的&GT;方式&gt;
是更好的解决方案。
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.
升压Python和智能指针很好地协同工作,可以在这个例子。
Boost Python and smart pointers work well together, which can be seen in this example.
要揭露矢量
s或列表
的使用索引接口,它可以被看作的这里
To expose vector
s or list
s use the indexing interface, which can be viewed here.
这篇关于Boost.Python的揭露函数返回矢量&lt;&MyClass的GT;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!