Boost.Python的揭露函数返回矢量<&MyClass的GT; [英] boost.python expose function that returns vector<MyClass>

查看:137
本文介绍了Boost.Python的揭露函数返回矢量<&MyClass的GT;的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在写C的扩展模块为Python ++和我使用Boost.Python的。我要揭露​​一个返回矢量&lt功能; MyClass的> 。我不完全知道如何做到这一点,将如何与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 vectors or lists use the indexing interface, which can be viewed here.

这篇关于Boost.Python的揭露函数返回矢量&lt;&MyClass的GT;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆