car*_*ose 33 c++ python cython
我拼命想把一个std::vector<bool>类成员公开给Python类.
这是我的C++类:
class Test
{
public:
std::vector<bool> test_fail;
std::vector<double> test_ok;
};
Run Code Online (Sandbox Code Playgroud)
虽然test_ok类型double(或int,float,..)的访问和转换有效,但它不适合bool!
这是我的Cython类:
cdef class pyTest:
cdef Test* thisptr
cdef public vector[bool] test_fail
cdef public vector[double] test_ok
cdef __cinit__(self):
self.thisptr = new Test()
self.test_fail = self.thisptr.test_fail # compiles and works if commented
self.test_ok = self.thisptr.test_ok
cdef __dealloc__(self):
del self.thisptr
Run Code Online (Sandbox Code Playgroud)
我得到的错误是:
Error compiling Cython file:
------------------------------------------------------------
...
cdef extern from *:
ctypedef bool X 'bool'
^
------------------------------------------------------------
vector.from_py:37:13: 'bool' is not a type identifier
Run Code Online (Sandbox Code Playgroud)
我正在使用python 2.7.6和Cython 0.20.2(也试过0.20.1).
我也尝试过属性,但它也不起作用.
附录:我确实有from libcpp cimport bool我的pyx文件的顶部,以及矢量导入.
怎么了 ??我相信这可能是一个错误.谁知道如何规避这个?谢谢.
Ben*_*Ben 46
您需要做一些额外的C++支持.在.pyx文件的顶部,添加
from libcpp cimport bool
Run Code Online (Sandbox Code Playgroud)
我将在内部查看您可能需要的其他内容,例如std :: string和STL容器
我找到了一个有效的解决方法,尽管它可能不是最佳的。
我已经用 python 列表替换了类的成员类型pytest。
现在,转换是隐式完成的,如文档中所述:https ://docs.cython.org/en/latest/src/userguide/wrapping_CPlusPlus.html#standard-library
所有转换都会创建一个新容器并将数据复制到其中。容器中的项目被自动转换为相应的类型,这包括在容器内部递归地转换容器,例如字符串映射的C++向量。
现在,我的班级看起来像这样:
cdef class pyTest:
cdef Test* thisptr
cdef public list test_fail #now ok
cdef public list test_ok
cdef __cinit__(self):
self.thisptr = new Test()
self.test_fail = self.thisptr.test_fail # implicit copy & conversion
self.test_ok = self.thisptr.test_ok # implicit copy and conversion
cdef __dealloc__(self):
del self.thisptr
Run Code Online (Sandbox Code Playgroud)