gpt4 book ai didi

python - ctypes 是否为枚举和标志提供任何东西?

转载 作者:太空狗 更新时间:2023-10-30 00:57:57 24 4
gpt4 key购买 nike

我有一个 API,我想使用 python。该 API 包含使用 #define 实现的标志和枚举。

// it's just almost C so don't bother adding the typedef and parenthesis diarrhea here.
routine(API_SOMETHING | API_OTHERTHING)
stuff = getflags()
? stuff & API_SOMETHING

action(API_INTERESTING)
mode = getaction()
? mode == INTERESTING

如果现在忽略除枚举和标志之外的所有其他内容,我的绑定(bind)应将其转换为:

routine(["something", "otherthing"])
stuff = getflags()
if 'something' in stuff

action('interesting')
mode = getaction()
if mode == 'interesting'

ctypes 是否提供直接执行此操作的机制?如果不是,那么只需介绍一下您在 python 绑定(bind)中处理标志和枚举的“常用”工具。

最佳答案

为什么不对 enum 参数使用 c_uint,然后使用这样的映射(枚举通常是无符号整数值):

在 C 中:

typedef enum {
MY_VAR = 1,
MY_OTHERVAR = 2
} my_enum_t;

在 Python 中:

class MyEnum():
__slots__ = ('MY_VAR', 'MY_OTHERVAR')

MY_VAR = 1
MY_OTHERVAR = 2


myfunc.argtypes = [c_uint, ...]

然后您可以将 MyEnum 字段传递给该函数。

如果您想要枚举值的字符串表示,您可以在 MyEnum 类中使用 dictionary

关于python - ctypes 是否为枚举和标志提供任何东西?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3100704/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com