python - 如何在 cython 中按值访问枚举类型

标签 python enums cython

我收到了一些看起来像这样的代码:

在“header.hpp”中:

enum class my_enum_type {
    val1 = 0;
    ... 
}

在“header_lib.pyx”中:

cdef extern from "header.hpp":
    enum my_enum_type:
        val1 = 0;
        ...
...

稍后在“header_lib.pyx”中:

def foo():
    ...
    return my_enum_type.val1

我被告知这应该没有问题,但根据我刚才的经验,情况并非如此,并且在这篇文章中很明显:Defining enums in Cython code that will be used in the C part of code .

但是,如果我写“return val1”,它也不会自己识别“val1”。执行此操作的正确方法是什么?

最佳答案

您可以在 Cython 中声明一个 enum 为:

ctypedef enum options: OPT1, OPT2, OPT3

ctypedef enum options:
    OPT1,
    OPT2,
    OPT3

并且示例可以是:

def main():
    cdef options test
    test = OPT2
    f(test)

cdef void f(options inp):
    if inp == OPT1:
        print('OPT1')
    elif inp == OPT2:
        print('OPT2')
    elif inp == OPT3:
        print('OPT3')

运行 main() 时,您将看到 "OPT2" 被打印出来。您可以将变量 test 传递给 CC++ 函数,方法与此处显示的 cdef 相同功能。

关于python - 如何在 cython 中按值访问枚举类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23304237/

相关文章:

python - 如何根据数组中的特征的大小来标记特征?

python - 停止 ipcluster 引擎(IPython Parallel)

Python:将深度优先搜索转换为广度优先搜索列表的所有组合

python - 将 C 字符串公开给 NumPy 的最快方法?

python - 判断一个 Python 函数是否已经在 C 扩展中实现

python - 包装一个函数,该函数返回一个指向带有 ctypes 的 python 对象的指针

python - Hive Python UDF

c++ - 为什么 Visual Studio C++ 编译器拒绝将枚举作为模板参数?

c# - 如何在枚举上创建扩展方法 (c#)

java - 将概率分配给随机枚举对象