使用pybind11可将C++代码封装为Python模块,通过编写绑定代码并编译为共享库,实现高效调用。首先安装pybind11并获取头文件路径,然后在C++中定义函数和类,并使用PYBIND11_MODULE宏导出;接着通过g++或CMake编译生成模块文件;最后在Python中直接导入使用。支持STL容器、异常映射、默认参数及NumPy集成等高级特性,使C++功能在Python中如原生模块般运行。

用 C++ 结合 pybind11 封装库供 Python 调用,是实现高性能混合编程的常用方式。pybind11 是一个轻量级头文件库,能将 C++ 函数、类、变量等自然地暴露给 Python,且语法简洁,兼容 C++11 及以上标准。
安装 pybind11
使用 pybind11 前需确保已安装。推荐通过 pip 安装:
pip install pybind11
开发时还需包含其头文件。若通过 pip 安装,可通过以下命令查看头文件路径:
立即学习“Python免费学习笔记(深入)”;
python -m pybind11 --includes
该命令输出编译时需添加的 include 路径,如 -I/usr/include/python3.8 和 -I/path/to/pybind11/include。
编写简单的 C++ 封装代码
创建一个 C++ 文件(例如 example.cpp),封装一个加法函数和一个简单类:
#include#include int add(int a, int b) { return a + b; }
class Calculator { public: explicit Calculator(const std::string& name) : name(name) {} int multiply(int x, int y) { return x * y; } std::string greet() const { return "Hello from " + name; } private: std::string name_; };
// 绑定模块 PYBIND11_MODULE(example, m) { m.doc() = "A simple example module";
// 绑定函数 m.def("add", &add, "A function that adds two integers"); // 绑定类 pybind11::class_(m, "Calculator") .def(pybind11::init ()) .def("multiply", &Calculator::multiply) .def("greet", &Calculator::greet); }
编译生成 Python 模块
需要将 C++ 代码编译为 Python 可导入的共享库(.so 或 .pyd)。可使用 g++ 手动编译或借助 CMake。
方法一:使用 g++ 直接编译(适用于简单项目)
g++ -O3 -Wall -shared -std=c++11 -fPIC `python3 -m pybind11 --includes` example.cpp -o example`python3-config --extension-suffix`说明:
- -shared:生成共享库
- -fPIC:生成位置无关代码
- python3 -m pybind11 --includes:自动获取包含路径
- python3-config --extension-suffix:确保生成的文件名符合当前 Python 版本(如 example.cpython-310-x86_64-linux-gnu.so)
方法二:使用 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在 Python 中调用封装的模块
编译成功后,当前目录会生成 example.so(Linux/macOS)或 example.pyd(Windows)。在 Python 中直接导入:
import exampleprint(example.add(2, 3)) # 输出: 5
calc = example.Calculator("MyCalc") print(calc.greet()) # 输出: Hello from MyCalc print(calc.multiply(4, 5)) # 输出: 20
支持高级特性(可选扩展)
pybind11 支持更多功能,如:
- STL 容器自动转换:vector、map 等可直接传递
- 异常处理:C++ 异常可映射为 Python 异常
- 默认参数、重载函数:支持函数重载与默认值
- NumPy 集成:通过 pybind11/eigen.h 或 numpy.h 支持数组高效传递
例如,支持 vector 的函数:
#include#include std::vector
filter_positive(const std::vector & input) { std::vector result; for (int x : input) if (x > 0) result.push_back(x); return result; } // 在 PYBIND11_MODULE 中添加 m.def("filter_positive", &filter_positive);
Python 中可直接传 list,返回 list。
基本上就这些。只要写好绑定代码,编译正确,就能在 Python 中像原生模块一样使用 C++ 功能。不复杂但容易忽略细节,比如文件命名和编译选项。











