我想知道Python如何将自定义类的C++对象转换为Python对象。我需要对 Message 类做任何事情吗?
Message 是流中包含的自定义类。
文件:test.h
#include "Streaming.h" //Definition of class Message
vector<Message> subscribe_(string taskid){
vector<Message> vecMsg;
...
return vecMsg;
}
文件:Streaming_test.pyx
from libcpp.vector cimport vector
from libcpp.string cimport string
cdef extern from "Streaming.h":
cdef cppclass Message:
Message() except +
cdef extern from "test.h":
vector[Message] subscribe_(const string taskid) nogil
def __subscribe(string taskid):
cdef vector[Message] vecMsg
listMsg = []
vecMsg = subscribe_(taskid)
for i in range(vecMsg.size()):
listMsg.append(vecMsg[i])
return listMsg
文件:setup.py
#build: python setup.py build_ext --inplace
from distutils.core import setup, Extension
from Cython.Build import cythonize
ext = Extension("wrapper_streaming",
sources = ["streaming_test.pyx"],
language = "c++",
library_dirs = ["../../build"],
libraries = ["DolphinDBAPI","pthread","ssl","rt"],
include_dirs = ["/root/api-cplusplus/include"],
extra_compile_args = ["-std=c++11"]
)
setup(ext_modules=cythonize(ext, language_level = 3))
我尝试编译时出现的错误:
vecMsg = subscribe_(taskid)
for i in range(vecMsg.size()):
listMsg.append(vecMsg[i])
^
------------------------------------------------------------
streaming_test.pyx:115:23: Cannot convert 'Message &' to Python object
如何将Message类型对象转换为Python对象? 消息是流中包含的自定义类。
要使用 Cython 将 C++ 对象转换为 Python 对象,您可以创建一个 Cython 扩展模块,为 C++ 对象定义 Python 包装类并实现必要的转换函数。