pybind11 使用指南+示例
pybind11 使用指南+示例
简介
pybind11 是一个轻量级的仅头文件C++库,用于在Python和C++之间创建无缝的接口。它提供了以下主要特点:
- 类型安全:自动处理C++和Python之间的类型转换
- 低开销:最小化运行时性能损失
- 良好集成:与Python生态系统(如NumPy)完美兼容
- 现代C++支持:充分利用C++11/14/17特性
pybind11特别适合需要将高性能C++代码暴露给Python使用的场景,同时保持代码的简洁性和可维护性。
示例项目代码参考:https://gitcode.com/wang161019/DRC_SYSTEM_PYTHON
环境配置
必需组件
- Python 3.8或更高版本
- CMake 3.15或更高版本
- 支持C++17的编译器
- pybind11库(已包含在项目中)
详细配置步骤
-
确保项目目录中包含pybind11子模块
git submodule add https://github.com/pybind/pybind11.git git submodule update --init --recursive
-
在CMakeLists.txt中添加pybind11依赖
add_subdirectory(pybind11) pybind11_add_module(example example.cpp) target_link_libraries(example PRIVATE pybind11::module)
-
构建项目
mkdir build && cd build cmake .. -DCMAKE_BUILD_TYPE=Release cmake --build . --config Release
C++代码绑定给Python调用
基本绑定示例
#include <pybind11/pybind11.h>int add(int i, int j) {return i + j;
}PYBIND11_MODULE(example, m) {m.doc() = "pybind11 example plugin";m.def("add", &add, "A function that adds two numbers&