代码之家  ›  专栏  ›  技术社区  ›  Cheery

ctypes为枚举和标志提供了什么吗?

  •  5
  • Cheery  · 技术社区  · 15 年前

    // 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
    

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

    routine(["something", "otherthing"])
    stuff = getflags()
    if 'something' in stuff
    
    action('interesting')
    mode = getaction()
    if mode == 'interesting'
    

    ctypes是否提供了直接实现这一点的机制?如果不是的话,那就说说你在python绑定中处理标志和枚举的“常用”工具。

    2 回复  |  直到 15 年前
        1
  •  4
  •   Cheery    15 年前

    我自己回答这个问题有点失望。尤其是我从f*手册上找到的。

    http://docs.python.org/library/ctypes.html#calling-functions-with-your-own-custom-data-types

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

    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"])
    

        2
  •  3
  •   the_void    15 年前

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

    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

    如果需要枚举值的字符串表示形式,可以使用 dictionary