python - 使用 boost::python,如何将结构 vector 作为字典列表返回给 Python?

标签 python c++ boost boost-python

我有以下 C++ 代码:

    struct MyType { int x, y; };
    struct A { 
        std::vector<MyType> get_data();
    };

我想使用 Boost Python 连接到 Python,以便可以按以下方式使用它:

    a = A()
    ret = a.get_data();
    for r in ret:
        print('x=%d; y=%d;' % (r['x'], r['y']))

我现在拥有的是一个相当幼稚的东西:

    BOOST_PYTHON_MODULE(pyA) { 
        class_<A>("A").def("get_data", &A::get_data);
    }

如预期的那样,这给了我以下错误

     TypeError: No to_python (by-value) converter found for C++ type

当我尝试调用 get_data()来自 Python 代码的函数。

我在这里看到了描述如何使用 vector_indexing_suite 的帖子(例如 std::vector to boost::python::list)转换 std::vector<T>list对于某些类型 T (例如 float 、字符串),但我不确定如何扩展它来处理我的 struct -> dict 转换。任何帮助将不胜感激。

最佳答案

下文介绍了如何将您的 C++ 代码公开给 PythonMyType 需要重载“等于”比较运算符,而且 MyType 本身需要暴露给 Python

#include <boost/python.hpp>
#include <boost/python/suite/indexing/vector_indexing_suite.hpp>
using namespace boost::python;

struct MyType { 
    int x, y;  
    bool operator==(const MyType& data) const {
        return this->x == data.x && this->y == data.y;
    }   
};
struct A { 
    std::vector<MyType> get_data() const { return {{1,2},{3,4}};};
};

BOOST_PYTHON_MODULE(pyA) {
    class_<MyType>("MyType")
        .def_readwrite("x", &MyType::x)
        .def_readwrite("y", &MyType::y);
    class_<std::vector<MyType>>("MyList")
        .def(vector_indexing_suite<std::vector<MyType>>());
    class_<A>("A").def("get_data", &A::get_data);
}

下面稍微修改了 Python 脚本。 get_data() 返回类型是一个列表,因此需要这样访问它。如果您希望它成为一个字典,则在 Python 中将其转换为字典。

import pyA 

a = pyA.A()
ret = a.get_data();
for r in ret:
    print('x=%d; y=%d;' % (r.x, r.y))

关于python - 使用 boost::python,如何将结构 vector 作为字典列表返回给 Python?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54446714/

相关文章:

python - 如何使用具有不同特征维度的数据集训练 sklearn 分类器?

python - 如何使用 FreeTDS ODBC 连接到 SQL Server

c++ - C++11 中的内存排序与主内存刷新排序有关吗?

c++ - 使用 boost::bind 传递比预期更多的参数安全吗?

python - 关于tensorflow中session的解释

python - 在用户定义的函数中访问全局框架

c++ - 如何在 C++ 中将字符串数据存储在字符串二维数组中

c++ - Linux I/O 管理器

c++ - 如何在 C++ 中的 boost::future 中添加回调

c++ - 如何防止ptr_map在插入失败时释放数据