如何在 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 [Py2] 的 python3.5-config 獲得)編譯此檔案 −

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 標頭檔案的 public 關鍵字完成的。我們也可以用 Cython 編譯 Python 模組並自行建立標頭檔案/處理額外的樣板。

更新於: 10-Feb-2020

738 次瀏覽

開始您的 職業

透過完成課程獲得認證

開始
廣告
© . All rights reserved.