如何在 C++ 中使用 Python 物件?


以下是一個簡單 Python 物件被封裝和嵌入的示例。我們使用  .c 來實現,c++ 的步驟類似 −

class PyClass(object):
    def __init__(self):
        self.data = []
    def add(self, val):
        self.data.append(val)
    def __str__(self):
        return "Data: " + str(self.data)
cdef public object createPyClass():
    return PyClass()
cdef public void addData(object p, int val):
    p.add(val)
cdef public char* printCls(object p):
    return bytes(str(p), encoding = 'utf-8')

我們使用 cython pycls.pyx(對於 c++ 使用 --cplus)進行編譯,以分別生成包含原始碼和函式宣告的 .c 和 .h 檔案。現在,我們建立一個啟動 Python 的 main.c 檔案,然後就可以呼叫這些函數了 −

#include "Python.h"   // Python.h always gets included first.
#include "pycls.h"    // Include your header file.
int main(int argc, char *argv[]){
    Py_Initialize();   // initialize Python
    PyInit_pycls();    // initialize module (initpycls(); in Py2)
    PyObject *obj = createPyClass();
    for(int i=0; i<10; i++){
        addData(obj, i);
    }
    printf("%s\n", printCls(obj));
    Py_Finalize();
    return 0;
}

使用適當的標誌(你可以從 python-config 中獲得 python3.5-config [Py2])進行編譯,

gcc pycls.c main.c -L$(python3.5-config --cflags) -I$(python3.5-config --ldflags) -std=c99

將會建立與我們的物件進行互動的可執行檔案 −

./a.out
Data: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

所有這些都是透過使用 Cython 及其生成 .h 標頭檔案的白關鍵字實現的。我們也可以只使用 Cython 編譯一個 Python 模組,然後自己建立標頭檔案/處理額外的樣板程式碼。

更新日期:10-Feb-2020

738 次瀏覽

開啟您的 職業生涯

完成課程獲取認證

開始吧
廣告
© . All rights reserved.