使用pybind11可将C++代码封装为Python模块。首先安装pybind11并配置CMake构建系统,编写C++函数或类并通过PYBIND11_MODULE宏导出,利用py::class_绑定类成员,包含pybind11/stl.h支持STL容器与Python类型自动转换,最终通过cmake编译生成可导入的扩展模块。

如何用 pybind11 封装 C++ 代码供 Python 调用
在需要性能提升或复用已有 C++ 逻辑的场景中,将 C++ 代码暴露给 Python 使用是一种常见做法。pybind11 是一个轻量而强大的库,能将 C++ 函数、类、对象无缝绑定到 Python,语法简洁且依赖少。下面介绍从零开始使用 pybind11 的完整流程。
安装 pybind11 和构建工具
pybind11 本身是一个头文件库,但需要正确配置构建系统才能生成 Python 可导入的模块。
- 通过 pip 安装 pybind11 开发包:
pip install pybind11 - 推荐使用 CMake + pybind11 或 setuptools 构建扩展模块。
- 若使用 CMake,确保找到 pybind11 模块:
find_package(pybind11 REQUIRED)
编写简单的 C++ 绑定代码
假设有一个 C++ 函数想在 Python 中调用:
立即学习“Python免费学习笔记(深入)”;
// example.cpp #includeint add(int a, int b) { return a + b; } namespace py = pybind11; PYBIND11_MODULE(example, m) { m.doc() = "pybind11 example plugin"; m.def("add", &add, "A function that adds two numbers"); }
说明:
-
PYBIND11_MODULE定义导出模块名(example),不能加分号。 -
m.def()注册函数,参数依次为 Python 名称、函数指针、文档字符串。
使用 CMake 构建模块
创建 CMakeLists.txt 文件:
cmake_minimum_required(VERSION 3.10) project(example) find_package(pybind11 REQUIRED) pybind11_add_module(example example.cpp)
编译步骤:
mkdir build cd build cmake .. make
成功后会生成 example.cpython-xxx.so(Linux)或 example.pyd(Windows),可在 Python 中直接 import。
封装 C++ 类
pybind11 支持完整类绑定,包括构造函数、方法、属性等。
class MyClass {
public:
MyClass(const std::string &name) : name(name) {}
void greet() const {
std::cout << "Hello from " << name << "\n";
}
int get_value() const { return value; }
private:
std::string name;
int value = 42;
};绑定该类:
PYBIND11_MODULE(example, m) {
py::class_(m, "MyClass")
.def(py::init())
.def("greet", &MyClass::greet)
.def("get_value", &MyClass::get_value);
} Python 中使用:
```python import example obj = example.MyClass("Test") obj.greet() # 输出: Hello from Test print(obj.get_value()) # 输出: 42 ```处理复杂类型和 STL 容器
pybind11 支持自动转换常见 STL 类型,需包含对应头文件。
- 使用
#include后,std::vector、std::string、std::map 等可自动与 Python list、dict 互转。 - 例如返回 vector:
std::vectorget_numbers() { return {1, 2, 3, 4, 5}; } // 绑定 m.def("get_numbers", &get_numbers);
nums = example.get_numbers() print(nums) # [1, 2, 3, 4, 5]
基本上就这些核心操作。只要注意模块命名、构建方式和类型映射,就能高效实现 C++ 与 Python 的互操作。实际项目中建议结合 pytest 做接口测试,确保稳定性。











