Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

วิธีใช้ Python object ใน C++

ตัวอย่างการ wrap และ embed Python object เรียบง่าย ใช้ .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 (ใช้ --cplus สำหรับ C++) จะได้ .c และ .h file ที่มี source และ function declarations สร้าง main.c เริ่ม Python และเรียก functions:

#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;
}

คอมไพล์ด้วย flags ที่เหมาะสม (จาก python3.5-config หรือ python-config [Py2]):

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

จะได้ executable ที่ interact กับ object:

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

ทั้งหมดทำได้โดยใช้ Cython พร้อม public keyword ที่สร้าง .h header file หรือ compile python module ด้วย Cython แล้วจัดการ header/boilerplate เอง