python - 在 Cython 代码中定义将在代码的 C 部分中使用的枚举

标签 python enums cython cpython

我在 cython 头文件 api.pxd 中定义了 enum:

ctypedef enum InstructionType:
    default = 0
    end_if = 1
    end_loop = 2
    backward_jump_here = 4

我还检查了将 ctypedef 转换为 cdef 是否可行(但没有成功)。

我想在某些类的 __cinit__ 方法中使用这个枚举的值:

from api cimport Instruction, CLinVM, InstructionType

# (...) some other classes

cdef class EndIf(Noop):
   def __cinit__(self):
      self.type = InstructionType.end_if

我得到编译错误:

    self.type = InstructionType.end_if
                              ^
------------------------------------------------------------
 /home/(...)/instructions.pyx:149:35: 'InstructionType' is not a constant, 

有什么方法可以这样定义和使用枚举吗?

最佳答案

您不能通过它们所属的类型名访问枚举常量,无论是在 C、C++ 还是 Cython 中。您需要为其创建一个包装器 .pxd

关于python - 在 Cython 代码中定义将在代码的 C 部分中使用的枚举,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9341511/

相关文章:

python - 更改导入顺序会导致 Python 中的错误

c++ - 使用 Cython 将 metis 链接到包装的 C++ 模块

python:有效地将矩阵堆栈的切片 i 乘以矩阵的列 i

c++ - SWIG:如何将 boost::shared_ptr 包装到 std::vector?

python - 简化 SymPy 中的条件积分

rust - [Rust 枚举] : How to get data value from mixed type enum in rust?

python - 在四维 matplotlib 曲面中更改 Facecolors

c# - 用于引用公共(public)属性的静态实例和枚举

c - typedef 音符枚举,制作将频率映射到音符的静态数组

python - 导入错误 : Cython and gcc-5