Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/image-processing/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 具有类成员的pybind11缓冲协议_Python_C++_Pybind11 - Fatal编程技术网

Python 具有类成员的pybind11缓冲协议

Python 具有类成员的pybind11缓冲协议,python,c++,pybind11,Python,C++,Pybind11,我正在尝试使用pybind11绑定一个如下所示的结构 struct myStruct { int na; int nb; double* a; double* b; } py::class_<myStruct>(m, "myStruct") .def_property("a", [](myStruct &s) {return py::array<double>({s.na}, {sizeof(double), s.a};)},

我正在尝试使用pybind11绑定一个如下所示的结构

struct myStruct {
 int na;
 int nb;
 double* a;
 double* b;
}
py::class_<myStruct>(m, "myStruct")
    .def_property("a",
        [](myStruct &s) {return py::array<double>({s.na}, {sizeof(double), s.a};)},
        [](myStruct &s, py::array_t<double> val) {std::copy((double*) val.request().ptr, (double*) val.request().ptr + s.na, s.a);)}
    )
我不确定该怎么办。中的示例演示如何将缓冲区协议语义附加到对象,而不是类成员

我不能随意更改
myStruct
的接口以包含
std::vector
s,这样我就可以使用通常的
.def_readwrite()

我试过这样做

struct myStruct {
 int na;
 int nb;
 double* a;
 double* b;
}
py::class_<myStruct>(m, "myStruct")
    .def_property("a",
        [](myStruct &s) {return py::array<double>({s.na}, {sizeof(double), s.a};)},
        [](myStruct &s, py::array_t<double> val) {std::copy((double*) val.request().ptr, (double*) val.request().ptr + s.na, s.a);)}
    )

嘿,很可能不是最优雅的答案,但也许它给了你一个起点和临时解决方案。我认为你需要做的是使用共享指针

有人问了一些类似的问题,但我无法将其应用到您的示例中,只得到了与您相同的结果,数据没有任何更改

在您的特定示例中,对我有效的是使用共享的ptr,并为指针定义setter和getter函数,为pybin11类定义一个简单的def_属性

class\u数据{
公众:
int na;
std::共享的ptr a;
空集a(双a){*类a数据::a=a;};
双get_a(void){return*class_DATA::a;};
};
PYBIND11_模块(测试,m){
m、 doc()=“pybind11示例插件”;
//肋骨类
py::class_m(class_数据),py::dynamic_attr())
.def(py::init())//需要定义构造函数
.def_readwrite(“na”,&class_数据::na)
.def_属性(“a”、&class_数据::获取_a、&class_数据::设置_a、py::返回_值_策略::复制);
}