Using enums in ctypes.Structure

前端 未结 2 1061
刺人心
刺人心 2020-12-03 18:07

I have a struct I\'m accessing via ctypes:

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


        
相关标签:
2条回答
  • 2020-12-03 18:24

    Using c_int or c_uint would be fine. Alternatively, there is a recipe in the cookbook for an Enumeration class.

    0 讨论(0)
  • 2020-12-03 18:29

    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
    
    0 讨论(0)
提交回复
热议问题