官方简介
pybind11 is a lightweight header-only library that exposes C++ types in Python and vice versa, mainly to create Python bindings of existing C++ code. Its goals and syntax are similar to the excellent Boost.Python library by David Abrahams: to minimize boilerplate code in traditional extension modules by inferring type information using compile-time introspection.
google translate---->
pybind11是一个轻量级的“Header-only”的库,它将C++的类型暴露给Python,反之亦然。主要用于将已经存在的C++代码绑定到Python。pybind11的目标和语法都类似于boost.python库。通过使用编译时内省推断类型信息,最大限度地减少传统扩展模块中的样板代码。
C++代码api.cpp
#include <pybind11/pybind11.h> // 导入 pybind11 的 C++ 库
#include <iostream>
namespace py = pybind11;
int add(int i, int j) {
return i + j;
}
class Pet
{
public:
std::string name;
int age;
Pet() {}
Pet(const std::string name_, const int age_){
name = name_;
age = age_;
}
~Pet(){
std::cout << "destructed" << std::endl;
}
void setName(std::string name_)
{
name = name_;
}
const std::string getName()
{
return name;
}
};
PYBIND11_MODULE(api, m) { // 创建一个 Python 模块,名为 api ,用变量 m 表示
py::class_<Pet>(m, "Pet") // 用 class_ 可以绑定一个 C++ 的 class 或 struct
.def(py::init<const std::string, const int>(), py::arg("name") = "tom", py::arg("age") = 2) // 带有默认值的、关键字参数 构造函数初始化
.def_readwrite("name", &Pet::name) // 绑定类变量
.def_readonly("age", &Pet::age) // 绑定类变量并限制为只读(修改时会抛出 AttributeError 异常)
.def("setName", &Pet::setName) // 绑定类方法
.def("getName", &Pet::getName);
m.doc() = "pybind11 example plugin"; // 可选的模块说明
m.def("add", &add, "a function which adds two numbers", // 绑定函数
py::arg("i") = 2,
py::arg("j") = 3);
}
编译so文件
g++ api.cpp -o api.so -O3 -Wall -std=c++11 -shared -fPIC `python3 -m pybind11 --includes`
python调用
进入python终端后
Python 3.7.0 (default, Jun 28 2018, 13:15:42)
[GCC 7.2.0] :: Anaconda, Inc. on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import api
>>> api.add(i = 4,j = 5)
9
>>> p = api.Pet(age = 2233)
>>> p.name
'tom'
>>> p.age
2233
>>>