mm@R1-A007 ~/gordon_space/ctop $ cat example.c
//example.c
int fact(int n){
if(n<=1)
return 1;
else
return n*fact(n-1);
}
mm@R1-A007 ~/gordon_space/ctop $ cat wrap.c
//filename: wrap.c
#include<Python.h>
PyObject* warp_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",warp_fact,METH_VARARGS,"Caculate N!"}, // fact为模块名字,第三个参数为传值方式,最后一个为注释
{NULL,NULL} //估计是结束符吧
};
void initexample(){
PyObject* m;
m = Py_InitModule("example", exampleMethods);
}
mm@R1-A007 ~/gordon_space/ctop $ gcc -fpic -c -I /usr/include/python2.7 -I /usr/lib/python2.7/config example.c wrap.c
mm@R1-A007 ~/gordon_space/ctop $ ls
example.c example.o wrap.c wrap.o
mm@R1-A007 ~/gordon_space/ctop $ gcc -shared -o example.so example.o wrap.o
mm@R1-A007 ~/gordon_space/ctop $ ls
example.c example.o example.so wrap.c wrap.o
mm@R1-A007 ~/gordon_space/ctop $ python2.7
Python 2.7.1 (r271:86832, Sep 7 2011, 12:55:30)
[GCC 4.4.5] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import example
>>> dir(example)
['__doc__', '__file__', '__name__', '__package__', 'fact']
>>> example.fact(6)
//example.c
int fact(int n){
if(n<=1)
return 1;
else
return n*fact(n-1);
}
mm@R1-A007 ~/gordon_space/ctop $ cat wrap.c
//filename: wrap.c
#include<Python.h>
PyObject* warp_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",warp_fact,METH_VARARGS,"Caculate N!"}, // fact为模块名字,第三个参数为传值方式,最后一个为注释
{NULL,NULL} //估计是结束符吧
};
void initexample(){
PyObject* m;
m = Py_InitModule("example", exampleMethods);
}
mm@R1-A007 ~/gordon_space/ctop $ gcc -fpic -c -I /usr/include/python2.7 -I /usr/lib/python2.7/config example.c wrap.c
mm@R1-A007 ~/gordon_space/ctop $ ls
example.c example.o wrap.c wrap.o
mm@R1-A007 ~/gordon_space/ctop $ gcc -shared -o example.so example.o wrap.o
mm@R1-A007 ~/gordon_space/ctop $ ls
example.c example.o example.so wrap.c wrap.o
mm@R1-A007 ~/gordon_space/ctop $ python2.7
Python 2.7.1 (r271:86832, Sep 7 2011, 12:55:30)
[GCC 4.4.5] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import example
>>> dir(example)
['__doc__', '__file__', '__name__', '__package__', 'fact']
>>> example.fact(6)
720