cython问题:“bool”不是类型标识

2024-04-29 02:59:41 发布

您现在位置:Python中文网/ 问答频道 /正文

我正拼命地试图向Python类公开一个std::vector<bool>类成员。

这是我的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和Cython 0.20.2(也尝试过0.20.1)。

我也试过使用属性,但也不起作用。

附录:我的pyx文件顶部有from libcpp cimport bool,还有向量导入。

怎么了??我相信这可能是个虫子。有人知道怎么避开这个吗?谢谢。


Tags: fromtestselfokpubliccythonclassfail
3条回答

为了在cython中定义boolean对象,需要将它们定义为bint。根据here:“boolean int”对象的bint被编译为一个c int,但被强制作为booleans在Cython之间往返。

示例:

cdef bint boolean_variable = True

来源:types bint

<>你需要做一些额外的C++支持。在.pyx文件的顶部,添加

from libcpp cimport bool

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

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

我已经用python列表替换了pytest类的成员类型。

转换现在隐式完成,如文档中所述:http://docs.cython.org/src/userguide/wrapping_CPlusPlus.html#standard-library

All conversions create a new container and copy the data into it. The items in the containers are converted to a corresponding type automatically, which includes recursively converting containers inside of containers, e.g. a C++ vector of maps of strings.

现在,我的课看起来是这样的:

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

相关问题 更多 >