python - 如何使用 boost.python 将字典列表从 C++ 返回到 python 而不会泄漏内存?
问题描述
我有一些 C++ 代码,我想从 Python 中调用它。C++ 代码将字典列表返回给 python 代码。我使用 boost.python 来实现这一点,方式如下:
struct MyStruct {
int foo;
};
class MyClass
{
public:
std::vector<MyStruct> get_stuff();
};
struct MyStructConverter
{
static PyObject* convert(const std::vector<MyStruct>& v)
{
boost::python::list ret;
for (auto c : v) {
boost::python::dict *r = new boost::python::dict();
(*r)["foo"] = c.foo;
ret.append(boost::python::object(*r));
}
return boost::python::incref(ret.ptr());
}
};
/** Interface between C++ and Python
*/
BOOST_PYTHON_MODULE(glue)
{
boost::python::to_python_converter<std::vector<MyStruct>, MyStructConverter>();
class_<MyClass, boost::noncopyable>("MyClass")
.def("get_stuff", &MyClass::get_stuff);
}
这在我可以将数据从 C++ 传递到 python 的范围内起作用。但是,当如下使用时:
# test.py
x = MyClass()
while True:
u = x.get_stuff()
# do something with u
它泄漏内存(即python进程的VSZ不断增长,直到整个系统停止运行)。
我究竟做错了什么?我怎样才能避免这种情况?
解决方案
推荐阅读
- linter - 使用 webhint 时出现此错误的原因是什么:错误:找不到模块“@hint/utils-dom”?
- powershell - 如果必须将数据放入变量中,Powershell 函数将不起作用
- html - 在 div 或 box 容器上剪切 CSS 箭头
- javascript - 如何在jquery中使滚动页脚淡入?
- postgresql - 在 WHERE 子句中使用的所有列上创建索引是一种好习惯吗
- javascript - 如何从 Angular 组件检测 iframe 内表单的更改?
- php - 如何从单个谷歌帐户的多个谷歌日历中获取所有事件?
- python - 在 NanoPi NEO Air 上使用 RPi.GPIO_NP python-lib 的问题
- command-line - 生成包含目录中文件名的 txt 文件时参数列表太长
- c# - 在 C# 中使用 GMail API 创建过滤器