如何在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')我们使用cythonpycls.pyx(对于c++使用--cplus)进行编译,以生成一个.c和.h文件,分别包含源声明和函数声明。现在我们创建一个main.c文件来启动Python,我们准备调用这些函数-
#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模块,然后自己创建头文件/处理其他样板文件。