python的C擴展

    原來是搞c的,python有c的擴展接口,因此先學習,寫下來加深印象,google一下,網上不少例子,也有幾種擴展方法:常規python C API,SWIG,boost,pyrex等等。SWIG和boost是c++的實現,c++不是很熟,因此直接看的C API。python

    若是隻是要將現成的C文件擴展成python中的模塊,那麼C的API看着不是很難。c++

    首先在想要擴展的C文件後#include <python.h>函數

    而後須要三個API接口學習


導出函數,用來與c文件中的函數交互。參數self在c函數被用於內聯函數的時候纔用到,而args包括了全部c函數中的參數,
經過PyArg_ParseTuple()獲取args
PyObject* method(PyObject* self, PyObject* args);

方法列表,包含了全部在python中能夠使用的方法
static PyMethodDef exampleMethods[] =
{
{"method_name", method, METH_VARARGS, "Description..."},
{NULL, NULL}
};

初始化函數,必須以init開頭,若是欲使用的模塊名爲example,那麼初始函數名爲initexample
void initexample()
{
PyObject* m;
m = Py_InitModule("example", exampleMethods);
}

在build前須要一個setup腳本,用到了distutils模塊ui

from distutils.core import setup, Extension
setup(name="example", version="1.0",
                ext_modules=[Extension("example", ["example.c"])])google

最後就是編譯spa

$python setup.py buildprototype

個人文件以下code

[code]接口

#include <stdio.h>
#include <stdlib.h>
#include <stdio.h>
#include <stdlib.h>
int iteract_sum(int n)
{
        if(n <= 1)
                return n;              
        else           
                return n + iteract_sum(n - 1); 
}

#include <Python.h>
static PyObject* Ext_sum(PyObject* self, PyObject* args)
{
        int n, result;
        if(! PyArg_ParseTuple(args, "i:iteract_sum", &n))
                return NULL;
        result = iteract_sum(n);
        return Py_BuildValue("i", result);
}

static PyMethodDef Methods[]=
{
        {"Ext_sum", Ext_sum, METH_VARARGS, "Caculate sum from 1 to n!"},
        {NULL, NULL}
};

PyMODINIT_FUNC initext(void)
{
        Py_InitModule3("ext", Methods, "do sth.");
}

[/code]

我在cygwin裏編譯的結果

$ python ext-setup.py build
running build
running build_ext
building 'ext' extension
gcc -fno-strict-aliasing -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -I/usr/include/python2.5 -c ext.c -o build/temp.cygwin-1.5.25-i686-2.5/ext.o
creating build/lib.cygwin-1.5.25-i686-2.5
gcc -shared -Wl,--enable-auto-image-base build/temp.cygwin-1.5.25-i686-2.5/ext.o -L/usr/lib/python2.5/config -lpython2.5 -o build/lib.cygwin-1.5.25-i686-2.5/ext.dll

最後是生成dll的動態連接庫

直接在python中就能夠import ext了,湊合着用用也行了,呵呵

相關文章
相關標籤/搜索