在ctypes.Structure中使用枚举 [英] Using enums in ctypes.Structure

查看:1164
本文介绍了在ctypes.Structure中使用枚举的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  struct attrl {
char * name;
char *资源;
char * value;
struct attrl * next;
枚举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),
但是我不知道该用于$ code> batch_op 枚举的用法。我应该把它映射到一个 c_int 或?

解决方案

至少对于GCC 枚举只是一个简单的数字类型。它可以是8位,16位,32位,64位或任何(我用64位值测试)以及签名无符号。我想它不能超过 long long int ,但实际上你应该检查你的枚举的范围,并选择类似 c_uint



这是一个例子。 C程序:

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

struct attrl {
char * name;
struct attrl * next;
枚举batch_op op;
};

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

和Python一个:


$ b $从ctypes导入(结构,c_char_p,c_uint,c_int,
POINTER,CDLL)

class AttrList(结构):$ pre> $ code $ b AttrList._fields_ = [
('name',c_char_p),
('next',POINTER(AttrList)),
('op',c_int),
]

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

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

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


I have a struct I'm accessing via ctypes:

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

So far I have Python code like:

# 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. Should I just map it to a c_int or ?

解决方案

At least for GCC enum is just a simple numeric type. It can be 8-, 16-, 32-, 64-bit or whatever (I have tested it with 64-bit values) as well as signed or unsigned. I guess it cannot exceed long long int, but practically you should check the range of your enums and choose something like c_uint.

Here is an example. The C program:

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:

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

这篇关于在ctypes.Structure中使用枚举的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆