pybind11 native python 模块简单试用
pybind11 是一个很不错的python c++ 互交互以及原生模块开发框架,可以快速服用c 以及c++ 周边的工具包对于python能力进行扩展
以下是一个简单使用,内容来自官方文档,主要是体验下
环境准备
我基于linux 构建,原生python 版本比较低,使用了miniconda 安装新的
- venv 环境
python3.12 -m venv venv
source venv/bin/activate
- 安装pybind11 pip 包
pip install pybind11
简单示例
来自官方的add 模块
- example.cpp
#include <pybind11/pybind11.h>
int add(int i, int j) {
return i + j;
}
PYBIND11_MODULE(example, m) {
m.doc() = "pybind11 example plugin"; // optional module docstring
m.def("add", &add, "A function that adds two numbers");
}
- 构建
此处我使用了自己的python 位置
c++ -O3 -Wall -shared -std=c++11 -fPIC $(/opt/pybind/venv/bin/python -m pybind11 --includes) example.cpp -o example$(/root/miniconda3/bin/python3.12-config --extension-suffix)
效果
- 使用app.py
import example
result = example.add(1,3)
print(result)
效果
说明
以上是一个简单试用,实际上pybind11 提供了比较完整的构建支持(cmake,bazel,meson,setuptools,cppimport),后边会演示下
参考资料
https://pybind11.readthedocs.io/en/stable/installing.html
https://pybind11.readthedocs.io/en/stable/compiling.html#compiling