首页 > 解决方案 > 如何使用 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不断增长,直到整个系统停止运行)。

我究竟做错了什么?我怎样才能避免这种情况?

标签: pythonc++boostmemory-leaksboost-python

解决方案


推荐阅读