参考官网文档:https://pybind11.readthedocs.io/en/stable/index.html
想象你在 Python 里写了个计算器,但跑得太慢,想用 C++ 提速,又不想完全抛弃 Python。Pybind11 就像一座桥,把 C++ 的高性能代码“嫁接”到 Python 里。你可以用 Python 调用 C++ 函数,就像请了个跑得飞快的帮手来干活。
安装 Pybind11:
安装 Python 和 CMake:
写个简单 C++ 文件: 新建 example.cpp:
int add(int a, int b) {
return a + b;
}
我们要让 Python 能调用这个 add 函数。
#include
int add(int a, int b) {
return a + b;
}
PYBIND11_MODULE(example, m) {
m.doc() = "一个简单的加法模块"; // 模块描述
m.def("add", &add, "加两个数", pybind11::arg("a"), pybind11::arg("b"));
}
编译成模块:
from setuptools import setup
from pybind11.setup_helpers import Pybind11Extension
ext_modules = [
Pybind11Extension(
"example", # 模块名
["example.cpp"], # 源文件
),
]
setup(
name="example",
ext_modules=ext_modules,
)
命令行运行:
python setup.py build_ext --inplace
成功后会生成一个 example.xxx.pyd(Windows)或 example.xxx.so(Linux/Mac)。
import example
print(example.add(3, 4)) # 输出 7
print(example.__doc__) # 输出 “一个简单的加法模块”
怎么回事?
改 example.cpp:
#include
int add(int a, int b = 10) {
return a + b;
}
PYBIND11_MODULE(example, m) {
m.def("add", &add, "加两个数", pybind11::arg("a"), pybind11::arg("b") = 10);
}
import example
print(example.add(5)) # 输出 15(5 + 10)
print(example.add(5, 3)) # 输出 8(5 + 3)
让 C++ 处理 Python 传来的列表:
#include
#include
std::vector<int> double_list(std::vector<int> lst) {
for (int& x : lst) x *= 2;
return lst;
}
PYBIND11_MODULE(example, m) {
m.def("double_list", &double_list, "把列表每个数翻倍");
}
import example
print(example.double_list([1, 2, 3])) # 输出 [2, 4, 6]
定义一个 C++ 类给 Python 用:
#include
class Pet {
public:
Pet(const std::string& name) : name(name) {}
void setName(const std::string& new_name) { name = new_name; }
std::string getName() const { return name; }
private:
std::string name;
};
PYBIND11_MODULE(example, m) {
pybind11::class_<Pet>(m, "Pet")
.def(pybind11::init<const std::string&>()) // 构造函数
.def("setName", &Pet::setName) // 方法
.def("getName", &Pet::getName); // 方法
}
import example
p = example.Pet("小狗")
print(p.getName()) # 输出 “小狗”
p.setName("小猫")
print(p.getName()) # 输出 “小猫”
提速:
python setup.py build_ext --inplace -DCMAKE_CXX_FLAGS="-O3"
调试:
python setup.py build_ext --inplace --verbose
试试这个任务:
#include
int multiply(int a, int b = 2) {
return a * b;
}
PYBIND11_MODULE(math_ops, m) {
m.def("multiply", &multiply, "乘法", pybind11::arg("a"), pybind11::arg("b") = 2);
}
用 Pybind11 编译成模块。
在 Python 中测试:
import math_ops
print(math_ops.multiply(5)) # 输出 10
print(math_ops.multiply(5, 3)) # 输出 15
通过这个教程,你应该能轻松用 Pybind11 把 C++ 的“超能力”带到 Python 里,像搭积木一样简单!如果有问题私信我,我再帮你细化解决。