4

I have searched and searched, but I haven't found an example that does what I need to do.
I found How can I represent an 'Enum' in Python? here on SO, but it doesn't cover ctypes.Structure. I also found Using enums in ctypes.Structure here on SO, but it includes pointers, which I am not familiar with.

I have a header file that includes typedef enum, that I need to use in a ctypes.Structure in a Python file.

C++ header file:

typedef enum {

        ID_UNUSED,
        ID_DEVICE_NAME,
        ID_SCSI,
        ID_DEVICE_NUM,
} id_type_et; 

Python file (The way I am currently doing it):

class IdTypeEt(ctypes.Structure):

        _pack_ = 1
        _fields_ = [ ("ID_UNUSED", ctypes.c_int32),
            ("ID_DEVICE_NAME", ctypes.c_char*64),
            ("ID_SCSI", ctypes.c_int32),
            ("ID_DEVICE_NUM", ctypes.c_int32) ]

Any advice would be greatly appreciated. The simpler, the better.

Community
  • 1
  • 1
KCReed
  • 43
  • 1
  • 3

1 Answers1

6

An enum is not a structure, it's an integral type with a pre-defined set of values (the enumerator constants). It doesn't make sense to represent it with ctypes.Structure. You're looking for something like this:

from ctypes import c_int

id_type_et = c_int
ID_UNUSED = id_type_et(0)
ID_DEVICE_NAME = id_type_et(1)
ID_SCSI = id_type_et(2)
ID_DEVICE_NUM = id_type_et(3)
Angew is no longer proud of SO
  • 167,307
  • 17
  • 350
  • 455
  • Is it safe to assume that the underlying values are always 0, 1, 2, 3, ... ? – 101 Mar 16 '15 at 04:32
  • 1
    @figs If the C++ header looks like the OP showed, yes. If the first enumerator is not given an explicit value, it's guaranteed to be 0. If a subsequent enumerator is not given an explicit value, it's guaranteed to be `previous enumerator + 1`. – Angew is no longer proud of SO Mar 16 '15 at 08:00