转自:
http://blog.163.com/wang_ly2442/blog/static/9494340720145955711249/
http://blog.csdn.net/fxjtoday/article/details/6059874
1. 新建wrapper.c,代码如下:
#include <Python.h>
int fact(int n)
{
if (n <= 1)
return 1;
else
return n * fact(n - 1);
}
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);
}
2. 把这段代码编成so库:
gcc -fPIC wrapper.c -o example.so -shared -I/usr/include/python2.6
3. 新建python脚本文件test.py:
#!/usr/bin/python
import example
a=example.fact(4)
print a
4. 运行python脚本:
[root@localhost python]# python test.py
24
可见输出正确的结果24