使用pybind11为Python编写一个简单的C语言扩展模块

相关:

为Python编写一个简单的C语言扩展模块

 

 

在Pybind11 出现之前为Python编写扩展模块的方法有多种,但是并没有哪种方法被认为一定比其他的好,因此也就变得在为Python编写扩展模块时就是白菜萝卜各有所爱了,用哪种方式编写扩展的都有,不过自从Pybind11出现后变成为了混合编程的解决方案的首选了。

具体参见:https://zhuanlan.zhihu.com/p/147994828

 

 

 

-----------------------------------------------------------------

 

 

 

以下操作均在Ubuntu22.04系统上,Python环境为系统原生自带的Python3.10版本。

 

 

1. 配置Python环境

由于需要安装pybind11,而pybind11需要和Python运行环境进行混编,因此需要用到Python的库文件,此时就不建议使用anaconda环境创建Python环境了,这时候我们需要有一个Python的库文件可控的Python环境,此时的需要使用的Python环境可以是系统原生自带的也可以是后期自我编译的,这里为了方便就直接使用了系统Ubuntu22.04自带的Python环境了。

 

 

安装系统自带Python的其他相关组件:

sudo apt install gcc

sudo apt install g++

sudo snap install cmake --classic

sudo apt install python3-dev

sudo apt install  python3-pip

sudo apt install python3.10-venv

 

 

 

为保证运行环境的沙盒特性使用python的venv来创建虚拟环境:

python3 -m venv test

 

 

 

 

激活创建好的Python环境:

source test/bin/activate

 

 

 

 

退出激活的Python环境:

deactivate

 

 

 

 

 

-----------------------------------------------------

 

 

 

为创建后的Python环境安装组件:

pip install pytest

 

 

 

-----------------------------------------------------

 

 

 

下载pybind11源码:

git clone https://github.com/pybind/pybind11

 

 

编译pybind11:

 

mkdir build
cd build
cmake ..
make check -j 4

 

 

 

 

 

 

编译成功:

 

 

 

 

 

 

 

从编译后的pybind11中进行安装:

python setup.py install

 

 

 

 

 

 

 

------------------------------------------------------

 

 

 

一个简单的pybind11例子,使用pybind11为Python编写扩展:

 

创建文件example.cpp

touch example.cpp

 

 

 

 

编写example.exe内容:

#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");
}

 

 

 

 

 

使用C++编译方式编译为动态链接库:

c++ -O3 -Wall -shared -std=c++11 -fPIC $(python3 -m pybind11 --includes) example.cpp -o example$(python3-config --extension-suffix)

 

 

 

 

 

 

 

 

使用Python调用刚才编译的C++动态库:

 

 

 

 

 

--------------------------------------------------------------------

 

 

上面的pybind源码编译安装的方法比较复杂,绝大部分人是没必要这么安装的,我们可以选择pip方式的安装:

 

pip install pybind11

 

 

 

 

---------------------------------------------------------------

 

 

 

pybind11源码地址:

https://github.com/pybind/pybind11

 

pybind11说明文档:

https://pybind11.readthedocs.io/en/latest/index.html

 

 

pybind11的官方例子:

https://github.com/pybind/python_example

 

posted on 2022-06-23 12:57  Angry_Panda  阅读(315)  评论(0编辑  收藏  举报

导航