Python ctypes是否为枚举和标志提供任何内容?

Python ctypes是否为枚举和标志提供任何内容?,python,ctypes,Python,Ctypes,我想从python中使用一个API。该API包含用#define实现的标志和枚举 如果现在忽略除枚举和标志之外的所有其他内容,则我的绑定应将其转换为: routine(["something", "otherthing"]) stuff = getflags() if 'something' in stuff action('interesting') mode = getaction() if mode == 'interesting' ctypes是否提供了直接执行此操作的机制?如果不是

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

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

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

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

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

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

在C中:

在Python中:

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

    MY_VAR = 1
    MY_OTHERVAR = 2


myfunc.argtypes = [c_uint, ...]
然后可以将
MyEnum
字段传递给函数


如果您想要枚举值的字符串表示形式,可以在
MyEnum
类中使用
字典。尤其是我从f*手册中找到的

为了完成我的回答,我将编写一些代码来包装一个项目

from ctypes import CDLL, c_uint, c_char_p

class Flag(object):
    flags = [(0x1, 'fun'), (0x2, 'toy')]
    @classmethod
    def from_param(cls, data):
        return c_uint(encode_flags(self.flags, data))

libc = CDLL('libc.so.6')
printf = libc.printf
printf.argtypes = [c_char_p, Flag]

printf("hello %d\n", ["fun", "toy"])

encode_标志将漂亮的列表转换为整数。

是。可以这样做。虽然我正在寻找一个自动形式的flag->text form转换。您可以重写
\uu getattr\uuu
方法来返回flag的文本表示形式,或者在类中定义其他静态字符串变量。我确信现在,既然
您已经阅读了文档
,那么,您知道,除了所有其他解决方案之外,您还可以使用
属性
class MyEnum():
    __slots__ = ('MY_VAR', 'MY_OTHERVAR')

    MY_VAR = 1
    MY_OTHERVAR = 2


myfunc.argtypes = [c_uint, ...]
from ctypes import CDLL, c_uint, c_char_p

class Flag(object):
    flags = [(0x1, 'fun'), (0x2, 'toy')]
    @classmethod
    def from_param(cls, data):
        return c_uint(encode_flags(self.flags, data))

libc = CDLL('libc.so.6')
printf = libc.printf
printf.argtypes = [c_char_p, Flag]

printf("hello %d\n", ["fun", "toy"])