【问题标题】:Get data from a list returned by a python function using c++ boost::python?使用 c++ boost::python 从 python 函数返回的列表中获取数据?
【发布时间】:2020-10-28 19:18:16
【问题描述】:

我有一个 python 函数返回一个浮点列表:

# Script.py
def get_double_list():
    data_list = []
    for a in range(5):
        data_list.append(float(a/10));
    return data_list

我想从 C++ 代码中调用它并从列表中获取数据。 我编写了以下 C++ 代码,但提取双打不起作用。 我做错了什么?

#define BOOST_AUTO_LINK_NOMANGLE
#include <boost/python.hpp>
#include <iostream>

namespace bp = boost::python;

int main(int argc, char** argv)
{

    Py_Initialize();
    boost::python::object main_module = boost::python::import("__main__");
    boost::python::dict main_namespace = boost::python::extract<boost::python::dict>(main_module.attr("__dict__"));

    exec_file("Script.py", main_namespace, main_namespace);

    boost::python::object global(main_module.attr("__dict__"));
    boost::python::object get_double_list = global["get_double_list"];

    if (!get_double_list.is_none())
    {
        auto py_ex_list = bp::extract<bp::list>(get_double_list());
        if (py_ex_list.check())
        {
            bp::list py_list = py_ex_list();
            Py_ssize_t list_len = bp::len(py_list);
            std::cout << "List length is: " << list_len << std::endl;
            for (Py_ssize_t i = 0; i < list_len; i++)
            {
                auto item = py_list[i];
                auto d_ex = bp::extract<double>(item);
                double d = d_ex();
                std::cout << "Double = " << d << std::endl;
            }
        }
    }
    return 0;
}

我知道它在某种程度上失败了

auto d_ex = bp::extract<double>(item);

(在 MS Windows 10、Boost 1.73.0、Python 3.8.5 上测试)

【问题讨论】:

    标签: c++ boost-python


    【解决方案1】:

    如果我将 data_list 更改为全局,它就可以工作

    data_list = []
    
    def get_double_list():
        global data_list
        for a in range(5):
            data_list.append(float(a/10));
        return data_list
    

    【讨论】:

    • 嗯,很烦人必须在 python 代码中进行调整,但很高兴你找到了解决方法。
    猜你喜欢
    • 2017-06-21
    • 1970-01-01
    • 1970-01-01
    • 2011-06-18
    • 2020-12-07
    • 1970-01-01
    • 2018-04-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多