C 扩展大概就是使用 Python 提供的方法将 C 代码在封装一遍。Python 提供了 Python.h 头文件,使用这些接口将 C 进行包装,最后编译成 so 文件(在windows下是dll)
编写 C 扩展需要三部分,缺一不可。
导出函数
方法列表
初始化函数
Example
最主要的是先封装C函数,接下来举个例子,我的系统是 Ubuntu 14.04,Python2.7
定义函数
比方用 C 写一个两数相加的方法 plus,文件名为 sample.c
1 2 3 4
intplus(int n, int m) { return n + m; }
导出函数
将该方法使用 Python 提供的API封装,首先导入头文件 Python.h
1 2 3 4 5 6 7 8 9 10
#include<Python.h>
static PyObject* wrap_plus(PyObject* self, PyObject* args) { int n, m, result; if (!PyArg_ParseTuple(args, "ii:plus", &n, &m)) returnNULL; result = plus(n, m); return Py_BuildValue("i", result); }