【发布时间】: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