C扩展python实例

来源:互联网 发布:最好的足球数据网站 编辑:程序博客网 时间:2024/05/16 10:09
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)

720



原创粉丝点击