gpt4 book ai didi

python - 在 ctypes.Structure 中使用枚举

转载 作者:太空狗 更新时间:2023-10-29 18:26:03 26 4
gpt4 key购买 nike

我有一个通过 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 位值对其进行了测试)以及 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

关于python - 在 ctypes.Structure 中使用枚举,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1546355/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com