结构体 binding
struct Pet源代码:
struct Pet {
Pet(const std::string &name) : name(name) { }
void setName(const std::string &name_) { name = name_; }
const std::string &getName() const { return name; }
std::string name;
};
binding code :
#include <pybind11/pybind11.h>
namespace py = pybind11;
PYBIND11_MODULE(example, m) {
py::class_<Pet>(m, "Pet")
.def(py::init<const std::string &>())
.def("setName", &Pet::setName)
.def("getName", &Pet::getName);
}
py::class_
是用来给C++ class 或者 struct-style 的数据结构创建binding的。
py:: init()
用来给相应的初始化函数创建binding。
% python
>>> import example
>>> p = example.Pet('Molly')
>>> print(p)
<example.Pet object at 0x10cd98060>
>>> p.getName()
u'Molly'
>>> p.setName('Charly')
>>> p.getName()
u'Charly'
See also
Static member functions
can be bound in the same way using class_::def_static().
Binding lambda functions
>>> print(p)
<example.Pet object at 0x10cd98060>
为了将打印的Pet信息可读性更高一些,可以通过定义__repr__
来实现,然而Pet
的定义中没有相应的function,我们在创建binding的时候不建议更改Pet的源代码。lambda function
可以轻松解决这个问题。
py::class_<Pet>(m, "Pet")
.def(py::init<const std::string &>())
.def("setName", &Pet::setName)
.def("getName", &Pet::getName)
.def("__repr__",
[](const Pet &a) {
return "<example.Pet named '" + a.name + "'>";
}
);
运行结果:
>>> print(p)
<example.Pet named 'Molly'>
ref:
https://pybind11.readthedocs.io/en/stable/classes.html