使用c语言扩展python

背景:我们工作中可能有时需要和第三方对接,而第三方提供的sdk可能是c语言或者c++编写的,而我们程序使用的语言是python,这时候就需要使用python调用c库

参考官方文档:https://docs.python.org/3/extending/extending.html

编写python扩展分三步:

第一步:创建应用代码

使用c语言编写具体的功能代码,如果sdk已经提供了并且不需要我们整合,则跳过这一步

第二步:根据样板编写封装代码

样板代码主要包含四部分

1. 包含Python头文件

2. 为每一个模块函数添加形如 static PyObject* Module_func()的封装函数

关于函数参数转换和返回值转换可以参考官方文档:https://docs.python.org/3/c-api/arg.html#

3. 将所有模块函数添加到static PyMethodDef ModuleMethods[]数组中,这是个二维数组

例如:

static PyMethodDef SpamMethods[] = {
    ...
    {"system"(函数名称),  spam_system(函数), METH_VARARGS(表示参数以元组的形式给定),
     "Execute a shell command."},
    ...
    {NULL, NULL, 0, NULL}        /* Sentinel */
};

  

4. 添加模块初始化函数void initModule,在初始化函数中调用Py_InitModule(“模块名”, ModuleMethods)进行初始化

第三步:编译并测试

使用distutils包来进行编译工作

1. 创建setup.py

from distutils.core import setup, Extension
setup(name="custom", version="1.0",
      ext_modules=[Extension("custom", ["custom.c"])])

 

2. 运行setup.py来编译并链接代码

1) python setup.py build 编译,会在当前目录下生成build文件夹

2) python setup.py install 安装,将编译好的包放到site-packages中

3. 在python中导入模块

4. 测试函数

 

posted @ 2020-06-14 16:18  CLAYJJ  阅读(220)  评论(0编辑  收藏  举报