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

新手上路,请多包涵

我拼命地试图将 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 许可协议

阅读 1.5k
2 个回答

我找到了一个有效的解决方法,尽管它可能不是最佳的。

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

原文由 Carmellose 发布,翻译遵循 CC BY-SA 4.0 许可协议

为了在 cython 中定义 boolean 对象,需要将它们定义为 bint 。根据 此处:“boolean int”对象的 bint 被编译为 ac int,但作为布尔值强制进出 Cython。

例子:

 cdef bint boolean_variable = True

来源: 类型 bint

原文由 Dalek 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题