cython 问题:"bool"不是类型标识符

cython issue: 'bool' is not a type identifier

本文关键字:类型 标识符 bool 问题 cython      更新时间:2023-10-16

我正在拼命地尝试将std::vector<bool>类成员暴露给Python类。

下面是我的c++类:
class Test
{
  public:
    std::vector<bool> test_fail;
    std::vector<double> test_ok;
};

虽然double(或int, float,…)类型的test_ok可以访问和转换,但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和cyth0.20.2(也尝试过0.20.1)。

我也尝试了属性,但它也不工作。

附录:我在pyx文件的顶部有from libcpp cimport bool,以及矢量导入。

怎么了??我想这可能是个bug。有人知道怎么规避吗?谢谢。

您需要做一些额外的c++支持。在.pyx文件的顶部,添加

from libcpp cimport bool

我会看一下里面,找到你可能需要的其他东西,比如std::string和STL容器

为了在cython中定义boolean对象,它们需要被定义为bint。根据这里:"boolean int"对象的int型被编译为c int型,但在Cython中被强制转换为布尔型。

的例子:

cdef bint boolean_variable = True

来源:types bint

我已经找到了一个有效的解决方案,尽管它可能不是最优的。

我已经用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