用C語言擴充Python的功能的執行個體

來源:互聯網
上載者:User

請點擊這裡查看關於用C語言擴充Python的功能。

只要安裝了Python,在用C進行Python的擴充編程時不需要額外安裝任何東西,Python會將標頭檔防置於/usr/include/python下,根據不同的版本稍有不同。

下面給出一個常式,它將產生一個可以被python匯入的模組,名為Example,其中包含一個splitwords的函數,這個函數接受兩個參數,第一個是包含單詞的字串,第二個是單詞的分隔字元,這也是一個字串,其中的每個字元都會用來作為分割單詞的字元。為方便起見,所有的函數都放置於一個檔案Example.c中。

// Filename Example.c

#include <Python.h>

PyObject* splitwords(const char *sz, const char *sp)
{
    // Python Objects
    PyObject *List = PyList_New(0);
    if (NULL == List || NULL == sz)
        return List;
    if (NULL == sp) {
        PyList_Append(List, Py_BuildValue("s", sz));
        return List;
    }
    // Split words
    const char *pbgn=NULL, *pend;
    size_t begin=0, end;
    size_t len = strlen(sz);
    char buf[0x20];
    while (begin < len) {
        if (strchr(sp, sz[begin])) {
            // String begins w/ 'sp'
            ++begin;
            continue;
        }
        else {
            size_t loc = begin;
            while (loc < len) {
                if (strchr(sp, sz[loc])) {
                    // Word stops here.
                    end = loc;
                    break;
                }
                else {
                    ++loc;
                    continue;
                }
            }
            if (loc == len) end = len;
            size_t l = end - begin;
            if (l >= 0x20) l = 0x19;
            strncpy(buf, sz+begin, l);
            buf[l] = '/0';
            //puts(buf);
            PyList_Append(List, Py_BuildValue("s", buf));
            // Next word
            begin = end;
        }
    }

    return List;
}

PyObject* wrap_splitwords(PyObject *self, PyObject *args)
{
    const char *sp, *sz;
    if (!PyArg_ParseTuple(args, "ss", &sp, &sz))
        return NULL;
    return (splitwords(sp, sz));
}

static PyMethodDef Methods[] = {
    {"splitwords", wrap_splitwords, METH_VARARGS, "Split Words"},
    {NULL, NULL, 0, NULL}
};

void initExample()
{
    PyObject *m;
    m = Py_InitModule("Example", Methods);
}

這裡產生的Python對象返回給Python,所以就不需要考慮引用計數的問題了。splitwords為C語言的擴充函數,用wrap_splitwords封裝,Example中的方法列表由Methods給出,初始化函數為initExample,只要看過上面的參考連結,這些都不需再解釋。

由於我的python版本是2.4.4,它的標頭檔目錄位於/usr/include/python2.4下。使用gcc來編譯,不要使用g++,以這個Example為例,由gcc產生的so中可以找到'initExample'符號,而g++產生的為'_Z15initExamplev',python在import時會出現找不到初始化函數的錯誤:

ImportError: dynamic module does not define init function (initExample)

如果一定要使用g++,或許可以將C++的擴充程式單獨放到一個檔案,從中產生一個靜態庫檔案,而封裝的程式仍使用gcc。這個設想還沒有實驗過,下面僅使用gcc:

gcc -fpic -c -I/usr/include/python2.4 -I/usr/lib/python2.4/config Example.c
gcc -shared -o Example.so Example.o

只要Example.so可以被找到(在python啟動並執行目前的目錄,或者是在/usr/lib下,或者由LD_LIBRARY_PATH指定)python就可以直接import:

>>> import Example
>>> s = 'ab,cde:ghij klmno'
>>> Example.splitwords(s, ' ')
['ab,cde:ghij', 'klmno']
>>> Example.splitwords(s, ' :')
['ab,cde', 'ghij', 'klmno']
>>> Example.splitwords(s, ' :,')
['ab', 'cde', 'ghij', 'klmno']

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.