您的位置:首页 > 编程语言 > Python开发

用C扩展python

2012-12-13 00:00 239 查看
今天准备毕业设计遇到了对python进行扩展的问题,简单记录下,以供以后参考。

先贴上代码,用实例讲解更易理解(这是在linux平台下做的实验):

文件Extest.c

#include <Python.h>
#include <stdio.h>

static PyObject *Extest_add(PyObject *self, PyObject *args) {
int a = 0;
int b = 0;

if(!PyArg_ParseTuple(args, "ii", &a, &b)) return NULL;

return (PyObject*)Py_BuildValue("i", a+b);
}

static PyMethodDef ExtestMethods[] = {
{"add", Extest_add, METH_VARARGS},
{NULL, NULL, 0}
};

void initExtest(void) {
Py_InitModule("Extest", ExtestMethods);
}
程序很简单的实现了两个整数相加,返回相加的值。

首先定义静态函数 static PyObject *Extest_add (...),函数命名方式:模块名+函数名。参数转换使用PyArg_ParseTuple 将args中的参数格式到a, b变量中,函数具体参数就不讲了google一下到处都有,使用Py_BuildValue 将C类型转为Python类型(关于C与python间的类型转换就不一一详解了,安装python后的帮助文档中C/Python API一部分中有更详细的解释)。

接着是定义静态数组变量 static PyMethodDef ExtestMethods[] = {...},来定义在python中的函数名为"add"

最后初始化模块函数 void initExtest(void) 构建名为"Extest"的模块。

完成C代码后,新建一个 setup.py文件,内容如下:

from distutils.core import setup, Extension

MOD = 'Extest'
setup (name=MOD, ext_modules = [
Extension(MOD, sources=['Extest.c'])])


完成后,执行命令 $python setup.py build

running build
running build_ext
building 'Extest' extension
gcc -pthread -fno-strict-aliasing -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes -fPIC -I/usr/include/python2.7 -c Extest.c -o build/temp.linux-i686-2.7/Extest.o
gcc -pthread -shared -Wl,-O1 -Wl,-Bsymbolic-functions -Wl,-Bsymbolic-functions build/temp.linux-i686-2.7/Extest.o -o build/lib.linux-i686-2.7/Extest.so

会在当前目录下生产build目录,进入目录有个lib,再进去,生成了一个Extest.so动态链接库。

写个程序测试下:

Extest.py:

import Extest

print Extest.add(1, 2)
显示 3,实验成功。。。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: