Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/348.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 在ctypes.Structure中使用枚举_Python_Enums_Ctypes - Fatal编程技术网

Python 在ctypes.Structure中使用枚举

Python 在ctypes.Structure中使用枚举,python,enums,ctypes,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", POIN

我有一个通过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),

但是我不确定批处理操作使用什么。我是否应该使用
c\u int
c\u int
将其映射到
c\u int
就可以了。或者,枚举类有一个简单的数字类型。

至少对于GCC
enum
来说,它只是一个简单的数字类型。它可以是8位、16位、32位、64位或其他(我用64位值测试过它)以及
有符号的
无符号的
。我猜它不能超过
long-long-int
,但实际上,您应该检查
enum
s的范围,并选择类似
c\u-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