系列文章
为c++类创建绑定
同样引用上一篇文章中的例子,我们将其改写成一个c++类
#include <pybind11/pybind11.h>
namespace py=pybind11;
using namespace std;
class Pet {
public:
Pet(const string &name) : name(name) {
}
void setName(const string &name_) {
name = name_; }
const string &getName() const {
return name; }
string name;
};
PYBIND11_MODULE(example3, m) {
py::class_<Pet>(m, "Pet")
.def(py::init<const std::string &>())
.def("setName", &Pet::setName)
.def("getName", &Pet::getName);
}
编译
c++ -O3 -Wall -shared -std=c++11 -fPIC `python3 -m pybind11 --includes` example3.cpp -o example3`python3-config --extension-suffix`
进行测试
$ ipython
Python 3.8.3 (default, Jul 2 2020, 16:21:59)
Type 'copyright', 'credits' or 'license' for more information
IPython 7.16.1 -- An enhanced Interactive Python. Type '?' for help.
In [1]: import example3