pybind11 - 使用 pybind11 绑定(bind)数组

标签 pybind11

我在c中有一个结构如下

typedef struct _person{
         int id[10];
         int number[10];
}person;

如何使用 pybind11 绑定(bind)它?

最佳答案

当您希望数据可写时,AFAICT 似乎没有一个很好的方法(当数据是只读时,它有点不那么人为)。不管怎样,假设你已经安装了 numpy,下面的方法就可以解决问题:

#include <pybind11/pybind11.h>
#include <pybind11/pytypes.h>
#include <pybind11/numpy.h>


typedef struct _person{
    int id[10];
    int number[10];
} person;

PYBIND11_MODULE(person, m)
{   
    pybind11::class_<person>(m, "person", pybind11::buffer_protocol())
        .def(pybind11::init<>())
        .def_property("id", [](person &p) -> pybind11::array {
            auto dtype = pybind11::dtype(pybind11::format_descriptor<int>::format());
            auto base = pybind11::array(dtype, {10}, {sizeof(int)});
            return pybind11::array(
                dtype, {10}, {sizeof(int)}, p.id, base);
        }, [](person& p) {})
        .def_property("number", [](person &p) -> pybind11::array {
            auto dtype = pybind11::dtype(pybind11::format_descriptor<int>::format());
            auto base = pybind11::array(dtype, {10}, {sizeof(int)});
            return pybind11::array(dtype, {10}, {sizeof(int)}, p.number, base);
        }, [](person& p) {});
}

问题是提供空的基础对象,使数组表现为 View 对象。没有基础,它就会复制。您不需要属性 setter (如果实现,将设置数组,而不是数组项),并且可能会引发错误,而不是像我那样提供无操作。另外,如果确实有两个相同大小的数组,则可以使用辅助函数而不是 lambda。

绑定(bind) C 内置数组的基本问题是 python 没有正确的数组类型(有基本的内存 View 和模块数组,但没有真正的数组类型),因此您需要从某处获取一个数组类型并 pybind11更喜欢使用 numpy 的游戏,因为它是城里最好的游戏。

只是为了向您展示另一种选择,在 cppyy ( http://cppyy.org ) 中,我采取了不同的策略:它有一个低级数组 View ,随后可以根据需要将其交给 numpy 进行查看或复制,因为它实现了全缓冲协议(protocol)。这里的优点是 python 用户可以决定最终的使用。缺点是如果你无论如何都要使用 numpy,那么这是一个额外的步骤。但它也可以在不安装 numpy 的情况下直接使用:

import cppyy

cppyy.cppdef("""
typedef struct _person{
    int id[10];
    int number[10];
} person;
""")

p = cppyy.gbl.person()
print(len(p.id), p.id)
print(list(p.id))

产生:

(10, <cppyy.LowLevelView object at 0x105ab33b0>)
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

关于pybind11 - 使用 pybind11 绑定(bind)数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58718884/

相关文章:

Pybind11 - 返回指向 unique_ptr 容器的指针

boost - Pybind11:可以使用 mpi4py 吗?

python - 如何将 c++ 类包装到 python 以便我可以使用 pybind11 访问其成员的公共(public)方法(成员是对象指针)

c++ - 不确定使用函数宏作为 C++ 程序入口点的概念,

cmake - 通过ExternalProject_Add 使用 pybind11 进行 CMake 项目的智能方法

python - 需要哪个 $path 以便 g++/pybind11 可以找到 Python.h?

c++ - 在Raspbian上编译pybind11测试用例时出现 fatal error

ubuntu-16.04 - 如何安装python-pybind11?

python - 如何通过pybind11在python中捕获C++的异常?

python - pybind11 包装现有代码