在封装中,我们可能会返回c/c++ struct类型的数据,那么其实最好的办法就是通过dict进行返回即可。
我想使用C ++代码返回C struct类型数据。但是我遇到了一个编译错误:
error: ‘__pyx_convert__to_py_Test’ has not been declared
难道我不能在Cython环境里用struct?
Cython生成的代码如下:
static PyObject* __pyx_convert__to_py_Test::mydata(struct Test::mydata s);
下面是其中示例代码:
libmy.h:
namespace Test {
struct mydata {
int id;
char name[256];
};
class Myclass {
mydata _data;
public:
const mydata & get_data() const;
};
}
libmy.cpp:
namespace Test {
const mydata & Myclass::get_data() const {
return const_cast(_data);
}
}
test.pxd:
cdef extern from "libmy.h" namespace "Test":
cdef struct mydata:
int id
char* name
cdef cppclass Myclass:
const mydata & get_data()
test.pyx:
cimport test as my
cdef class Py_Myclass:
cdef my.Myclass *thisptr
def __cinit__(self):
self.thisptr = new my.Myclass()
def __dealloc__(self):
del self.thisptr
def get_data(self):
return self.thisptr.get_data()
setup.py:
setup(
ext_modules = cythonize([Extension("mylib", ["mylib.pyx"], language="c++", libraries=["my"])])
)
当我在test.pxd文件中使用‘cppclass’替代‘struct’时,我遇到一个错误:
Cannot convert 'mydata const &' to Python object
于是我把:
cdef struct mydata:
改为:
cdef cppclass mydata:
最好的方式应该是:
我应该在'test.pyx'文件中创建一个包含C++ struct信息的python对象。
def get_data(self):
d = self.thisptr.get_data()
data = {}
data["id"] = d.id
data["name"] = d.name
return data
我也将C struct更改为'test.pxd'文件中的'cppclass'。
cdef cppclass mydata:
int id
char* name
文章的脚注信息由WordPress的wp-posturl插件自动生成
|2|left
打赏
微信扫一扫,打赏作者吧~