[英]Using enums in ctypes.Structure
I have a struct I'm accessing via ctypes: 我有一个通过ctypes访问的结构:
struct attrl {
char *name;
char *resource;
char *value;
struct attrl *next;
enum batch_op op;
};
So far I have Python code like: 到目前为止,我有类似以下的Python代码:
# struct attropl
class attropl(Structure):
pass
attrl._fields_ = [
("next", POINTER(attropl)),
("name", c_char_p),
("resource", c_char_p),
("value", c_char_p),
But I'm not sure what to use for the batch_op
enum. 但是我不确定在batch_op
枚举中使用什么。 Should I just map it to a c_int
or ? 我应该将其映射到c_int
还是?
At least for GCC enum
is just a simple numeric type. 至少对于GCC来说, enum
只是一个简单的数字类型。 It can be 8-, 16-, 32-, 64-bit or whatever (I have tested it with 64-bit values) as well as signed
or unsigned
. 它可以是8位,16位,32位,64位或其他任何值(我已经用64位值对其进行了测试),也可以是signed
或unsigned
。 I guess it cannot exceed long long int
, but practically you should check the range of your enum
s and choose something like c_uint
. 我猜它不能超过long long int
,但是实际上您应该检查enum
的范围并选择c_uint
类的c_uint
。
Here is an example. 这是一个例子。 The C program: 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;
}
and the Python one: 和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
Using c_int
or c_uint
would be fine. 使用c_int
或c_uint
可以。 Alternatively, there is a recipe in the cookbook for an Enumeration class. 另外, 食谱中也有一个针对Enumeration类的食谱 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.