在ctypes.Structure中使用枚举

时间:2009-10-09 22:25:12

标签: python enums ctypes

我有一个我通过ctypes访问的结构:

struct attrl {
   char   *name;
   char   *resource;
   char   *value;
   struct attrl *next;
   enum batch_op op;
};

到目前为止,我有Python代码:

# struct attropl
class attropl(Structure):
    pass
attrl._fields_ = [
        ("next", POINTER(attropl)),
        ("name", c_char_p),
        ("resource", c_char_p),
        ("value", c_char_p),

但我不确定如何使用batch_op枚举。我应该将其映射到c_int还是?

2 个答案:

答案 0 :(得分:9)

至少对于GCC enum来说只是一个简单的数字类型。它可以是8,16,32,64位或其他(我用64位值测试过)以及signedunsigned。我想它不能超过long long int,但实际上您应该检查enum的范围并选择c_uint之类的内容。

这是一个例子。 C程序:

enum batch_op {
    OP1 = 2,
    OP2 = 3,
    OP3 = -1,
};

struct attrl {
    char *name;
    struct attrl *next;
    enum batch_op op;
};

void f(struct attrl *x) {
    x->op = OP3;
}

和Python一:

from ctypes import (Structure, c_char_p, c_uint, c_int,
    POINTER, CDLL)

class AttrList(Structure): pass
AttrList._fields_ = [
    ('name', c_char_p),
    ('next', POINTER(AttrList)),
    ('op', c_int),
]

(OP1, OP2, OP3) = (2, 3, -1)

enum = CDLL('./libenum.so')
enum.f.argtypes = [POINTER(AttrList)]
enum.f.restype = None

a = AttrList(name=None, next=None, op=OP2)
assert a.op == OP2
enum.f(a)
assert a.op == OP3

答案 1 :(得分:5)

使用c_intc_uint会没问题。或者,枚举类有recipe in the cookbook