我拼命地试图将 std::vector<bool>
类成员暴露给 Python 类。
这是我的 C++ 类:
class Test
{
public:
std::vector<bool> test_fail;
std::vector<double> test_ok;
};
虽然访问和转换 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
我得到的错误是:
Error compiling Cython file:
------------------------------------------------------------
...
cdef extern from *:
ctypedef bool X 'bool'
^
------------------------------------------------------------
vector.from_py:37:13: 'bool' is not a type identifier
我正在使用 python 2.7.6 和 Cython 0.20.2(也尝试过 0.20.1)。
我也尝试过使用属性,但它也不起作用。
附录: 我的 pyx 文件顶部确实有 from libcpp cimport bool
以及矢量导入。
怎么了 ??我相信这可能是一个错误。任何人都知道如何规避这个?谢谢。
原文由 Carmellose 发布,翻译遵循 CC BY-SA 4.0 许可协议
我找到了一个有效的解决方法,尽管它可能不是最佳的。
我已经用 python 列表替换了
pytest
类的成员类型。转换现在隐式完成,如文档中所述: https ://docs.cython.org/en/latest/src/userguide/wrapping_CPlusPlus.html#standard-library
所以现在,我的班级看起来像这样: