17

我想使用 PyBind11 来包装一个专门的数组类。但是,该数组有多种形式(每种普通旧数据类型一种)。代码如下所示:

py::class_<Array2D<float>>(m, "Array2Dfloat", py::buffer_protocol(), py::dynamic_attr())
    .def(py::init<>())
    .def(py::init<Array2D<float>::xy_t,Array2D<float>::xy_t,float>())
    .def("size",      &Array2D<float>::size)
    .def("width",     &Array2D<float>::width)
    .def("height",    &Array2D<float>::height)
    //...
    //...

我想到告诉 PyBind11 这些类的唯一方法是通过使用一个非常大的宏为每个 POD 复制上述内容。

有一个更好的方法吗?

4

1 回答 1

27

您可以避免使用宏,而是使用模板化声明函数:

template<typename T>
void declare_array(py::module &m, std::string &typestr) {
    using Class = Array2D<T>;
    std::string pyclass_name = std::string("Array2D") + typestr;
    py::class_<Class>(m, pyclass_name.c_str(), py::buffer_protocol(), py::dynamic_attr())
    .def(py::init<>())
    .def(py::init<Class::xy_t, Class::xy_t, T>())
    .def("size",      &Class::size)
    .def("width",     &Class::width)
    .def("height",    &Class::height);
}

然后多次调用它:

declare_array<float>(m, "float");
declare_array<int>(m, "int");
...
于 2017-12-11T08:42:59.023 回答