欢迎您访问 最编程 本站为您分享编程语言代码,编程技术文章!
您现在的位置是: 首页

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

最编程 2024-07-15 09:52:25
...

 

在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

 

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

 

激活创建好的Python环境:

source test/bin/activate

 

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

  

退出激活的Python环境:

deactivate

 

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

 

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

 

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

pip install pytest

 

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

 

下载pybind11源码:

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

 

 

编译pybind11:

 

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

 

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

 

编译成功:

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

 

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

python setup.py install

 

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

 

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

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

 

创建文件example.cpp

touch example.cpp

 

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

 

编写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)

 

 

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

 

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

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

 

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

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

 

pip install pybind11

 

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

 

 

pybind11源码地址:

​https://github.com/pybind/pybind11​

 

pybind11说明文档:

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

 


pybind11的官方例子:

​https://github.com/pybind/python_example​

 

推荐阅读