Making opaque types
为了处理这种情况,pybind11 提供了PYBIND11_MAKE_OPAQUE(T)
的宏,这个宏使得类型转换不依赖于template-based conversion machinery of types。
这样一来是他们不透明。 opaque types 对象are never inspected or extracted, 因而可以通过引用进行传递。如将std::vector<int>
转为opaque类型, 在编写binding code前,先添加如下声明:
PYBIND11_MAKE_OPAQUE(std::vector<int>)
这个宏必须在程序顶部进行声明,并且不能在namespcae当中,因为这句宏会对模板的初始化进行重载,如果有多个编译单元,那么需要在每个源文件中使用std::vector<int>
前都要有这句宏,通常是共用一个头文件。
通常还会有一个class 来bind相关的operation,以便python能否调用相关操作。
py::class_<std::vector<int>>(m, "IntVector")
.def(py::init<>())
.def("clear", &std::vector<int>::clear)
.def("pop_back", &std::vector<int>::pop_back)
.def("__len__", [](const std::vector<int> &v) {
return v.size(); })
.def("__iter__", [](std::vector<int> &