【问题标题】:Pybind11: Wrap a struct with a pointer member?Pybind11:用指针成员包装结构?
【发布时间】:2021-09-18 09:31:24
【问题描述】:

我需要包装以下结构

struct dataStruct {
    const std::vector<int>& data;
    bool valid_data = true;
}

在我的包装文件中,在PYBIND11_MODULE 等下我有

py::class_<dataStruct>(m, "dataStruct")
   .def(py::init<>())
   .def_readwrite("data", &dataStruct::data)
   .def_readwrite("valid_data", &dataStruct::valid_data);

我遇到了两个错误

no instance of function template "pybind11::class_<type_, options...>::def_readwrite [with type_=dataStruct, options=<>]" matches the argument list -- argument types are: (const char [7], <error-type>) -- object type is: pybind11::class_<dataStruct>

pointer to member of type "const std::vector<int, std::allocator<int>> &" is not allowed

我知道这是由于结构中的指针造成的,但是在查看 pybind11 文档时,我不知道如何处理结构中的指针。

【问题讨论】:

  • Python 使用引用计数,因此使用对 std::vector 的原始引用是不行的。最重要的是,引用是一个无法修改的指针,因此为引用创建读/写属性已经被误导了。这将有助于更好地了解您的动机。您是否尝试为包含可以从 python 修改内容的向量 (data) 的结构 (dataStruct) 创建绑定?
  • 基本上我有这个 c++ 库(我没有写),我想完全暴露给 python,这是其中一个数据结构的稍微简化的版本(原来只是有更多结构成员)。我不认为我严格需要它是可写的,但绝对是可读的。 C++ 不是我的强项,所以我的目标只是在 python 中创建一个尽可能接近的 1:1 绑定。

标签: c++ pointers struct pybind11


【解决方案1】:

我之前所做的是围绕dataStruct 编写一个包装器结构,然后将其暴露给Python。这将允许您将向量的额外副本保留为实际的 Python 列表。

struct dataStructPy : dataStruct {
    const py::list & data_py;
}

然后您可以将data_py 设置为属性而不是读写,并且您可以编写在std::vectorpy::list 之间进行转换的get/set 函数。这允许您在 C++ 端使用 std::vector,同时在 Python 端使用标准 Python list。此类函数可能如下所示:

py::list dataStructPy::data_py_get()
{
    py::list list;
    for(const auto & x : this->data) {
        list.append(x);
    }

    return list;
}

void dataStructPy::data_py_set(const py::list & data_py)
{
    this->data.clear();
    for(int i = 0; i < py::len(data_py); ++i) {
        this->data.emplace_back(data_py[i]);
    }
}

然后您可以将dataStructPy 暴露给Python 并调用它dataStruct(您可以看到我们仍然暴露&amp;dataStruct::valid_data):

py::class_<dataStructPy>(m, "dataStruct")
   .def(py::init<>())
   .def_readwrite("valid_data", &dataStruct::valid_data);
   .add_property("data", &dataStructPy::data_py_get, &dataStructPy::data_py_set);

在 Python 中,执行以下操作

x = dataStruct()
x.data = [1, 2, 3, 4]

将导致 C++ x.data_py = py::list{1, 2, 3, 4};x.data = std::vector{1, 2, 3, 4};

注意:这仅适用于赋值运算符 (=)。如果在 Python 方面,如果您执行 x.data[3] = 5 它不会更新 C++ 向量,那么您需要创建一个对象来访问该向量的内存Python 使用 [] 运算符。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-27
    相关资源
    最近更新 更多