boost.python暴露返回向量的函数< MyClass> [英] boost.python expose function that returns vector<MyClass>

查看:198
本文介绍了boost.python暴露返回向量的函数< MyClass>的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在C ++中为Python编写了一个扩展模块,我使用boost.python。我想暴露一个返回向量< MyClass> 的函数。我不知道该如何做,以及它将如何与Python WRT内存管理交互。



我的第一个想法是包装 MyClass shared_ptr 中,因此该函数将返回 vector< shared_ptr< MyClass>> 。这会有帮助吗?当 shared_ptr< MyClass> 实例进入Python陆地时会发生什么?他们会被释放吗?



所以我的问题是:我如何公开一个函数返回一个向量 MyClass 实例到Python没有泄漏内存?



谢谢。

c>> 向量中的那些实例使用向量< MyClass> >显然(种类,因为向量内部使用动态分配的内存)堆栈分配。它将不同于向量< MyClass *> ,它实际上是动态分配的 MyClass 实例的向量。在这种情况下,向量< shared_ptr< MyClass> > 是更好的解决方案。



Boost Python和智能指针协同工作,可以在 this example。



公开 vector s或 list 使用索引界面,可以查看此处


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

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

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