作者热门文章
- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
我有一个通过 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
还是
最佳答案
至少对于 GCC enum
只是一个简单的数字类型。它可以是 8 位、16 位、32 位、64 位或其他任何类型(我已经用 64 位值对其进行了测试)以及 signed
或 unsigned
。我想它不能超过 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
关于python - 在 ctypes.Structure 中使用枚举,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1546355/
我是一名优秀的程序员,十分优秀!