介绍

PyBind11 是一个轻量级的 Python 绑定库,用于将 C++ 代码无缝集成到 Python 中。它通过 Python 的 C API 提供高效的绑定机制,适用于需要高性能计算的场景。

pybind11_guide

安装与配置

  1. 安装 PyBind11
    使用 pip 安装:
    pip install pybind11
    
  2. 集成到 C++ 项目
    CMakeLists.txt 中添加:
    find_package(pybind11 REQUIRED)
    add_subdirectory(pybind11)
    
    详情可参考本站文档:/extensions/pybind11/install

快速上手

创建模块

#include <pybind11/pybind11.h>
namespace py = pybind11;

PYBIND11_MODULE(my_module, m) {
    m.def("add", &add, "Add two numbers", py::arg("a"), py::arg("b"));
}
c_plus_plus_integration

绑定数据类型

  • 基本类型:自动支持 int, float, bool
  • 自定义类型:通过 py::class_ 注册
    py::class_<MyClass>(m, "MyClass")
        .def(py::init<>())
        .def("method", &MyClass::method);
    
  • 容器支持:列表、字典、数组等可直接映射
    m.def("process_list", [](const py::list& lst) {
        for (auto& item : lst) {
            // 处理逻辑
        }
    });
    

进阶技巧

性能优化

  • 使用 py::buffer 实现高效内存访问
  • 启用 PYBIND11_MODULE_EXPORTS 优化符号导出
pybind11_performance

异常处理

  • C++ 异常会自动转换为 Python 的 Exception
  • 通过 PYBIND11_NO_EXCEPTIONS 禁用异常支持(不推荐)
  • 详细用法见:/extensions/pybind11/exceptions

常见问题

  • Q: 如何调试绑定代码?
    A: 使用 pybind11::print() 输出调试信息
  • Q: 支持哪些 Python 版本?
    A: Python 3.6 及以上(推荐 3.8+)
  • Q: 如何处理 C++ 对象的生命周期?
    A: PyBind11 自动管理引用计数,无需手动干预

参考资料

python_cplusplus_bridge