C擴展python實例

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



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章