cython 问题:"bool"不是类型标识符
cython issue: 'bool' is not a type identifier
我正在拼命地尝试将std::vector<bool>
类成员暴露给Python类。
class Test
{
public:
std::vector<bool> test_fail;
std::vector<double> test_ok;
};
虽然double
(或int, float,…)类型的test_ok
可以访问和转换,但bool
不能!
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
相关文章:
- 在没有标识符的情况下如何读取复杂的C++类型声明?
- 在头文件中使用opencv类型来实现未定义的标识符
- 声明中类型和对象的相同标识符
- 无法将结构类型的标识符设置为 nullptr;
- 返回别名标识符,而不是typeid(SOME_TYPE).name()中的类型
- 未声明的标识符和类型"int"从 main 调用类时出现意外错误
- 什么时候可以将"typename"与明确引用类型的标识符一起使用?
- 使用函数模板中静态局部变量的地址作为类型标识符是否安全
- 使用标准类型的动态类型信息实例化标识符
- 在编译时生成唯一的类型标识符
- 声明枚举标识符的基础类型
- 错误:字符串常量之前的预期标识符或错误:'perf'不是类型
- 使用结构标识符表示POD类型和C结构
- 根据编译时常量,使用相同的标识符 #define 或类型定义是否被认为是可接受的做法?
- 为类型分配唯一的整型标识符,编译时
- cython 问题:"bool"不是类型标识符
- 为什么C基本类型有多个关键字的标识符
- 重新解释不带类型标识符的强制转换void
- 显式类型标识符与RTTI
- 通过类型标识符表示类的数字唯一标识符