操作系统:linux debian 4.0, python版本2.5
s1:安装python2.5-dev。因为Python.h是在dev包中才有。
test@debian:~/test_python_c$ aptitude search python2.5-dev
p python2.5-dev - Header files and a static library for Python.
test@debian:~/test_python_c$ sudo aptitude install python2.5-dev
...
test@debian:~/test_python_c$ aptitude search python2.5-dev
i python2.5-dev - Header files and a static library for Python.
s2:准备测试文件——C语言函数
//filename:example.c
int fact(int n)
{
if(n<=1)
return 1;
else
return n*fact(n-1);
}
s3: 编写封装接口
//filename: wrap.c
#include
PyObject* wrap_fact(PyObject* self, PyObject* args)
{
int n, result;
if (! PyArg_ParseTuple(args, "i:fact", &n))
return NULL;
result = fact(n);
return Py_BuildValue("i", result);
}
static PyMethodDef exampleMethods[] =
{
{"fact", wrap_fact, METH_VARARGS, "Caculate N!"},
{NULL, NULL}
};
void initexample()
{
PyObject* m;
m = Py_InitModule("example", exampleMethods);
}
s4:编译连接
gcc -fpic -c -I /usr/include/python2.5 -I /usr/lib/python2.5/config example.c wrap.c
gcc -shared -o example.so example.o wrap.o
test@debian:~/test_python_c$ ls
example.c example.o example.so wrap.c wrap.o
s5:测试example扩展模块
test@debian:~/test_python_c$ python
Python 2.5 (release25-maint, Jul 20 2008, 20:47:25)
[GCC 4.1.2 20061115 (prerelease) (Debian 4.1.1-21)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import example
>>> dir(example)
['__doc__', '__file__', '__name__', 'fact']
>>> example.fact(5)
120
>>> example.fact(16)
2004189184
>>> example.fact(17)
-288522240
说明fact(17)的时候溢出了。
操作系统:windowsXP, python版本2.5
#TODO: