pybind11 库

一个cpp 的 header only 库,用于将cpp的类型函数暴露给python使用。2017年发布,算一个比较新的库,目前有一些大型的库在使用pybind11,比如 numpy,pytorch,tensorflow,open3d等。

比如我定义一个类型:

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;
};

然后使用pybind11定义好暴露的类型和函数:

#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);
}

然后就可以通过python来直接调用:

% python
>>> import example
>>> p = example.Pet("Molly")
>>> print(p)
<example.Pet object at 0x10cd98060>
>>> p.getName()
'Molly'
>>> p.setName("Charly")
>>> p.getName()
'Charly'

教程:

https://daobook.github.io/pybind11/classes.html

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注