KCReed
KCReed

Reputation: 43

How can I convert a C++ enum to ctypes.Structure using Python 2.7.2?

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.

Upvotes: 4

Views: 3176

Answers (1)

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)

Upvotes: 6

Related Questions