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

I searched and searched, but I did not find an example that does what I need to do.
I found How can I introduce "Enum" in Python? here on SO, but it does not cover ctypes.Structure. I also found Using Enumerations in ctypes.Structure here on SO, but it includes pointers that I am not familiar with.

I have a header file that includes a typedef enum that I need to use in 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 (as I do it now):

 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.

+4
source share
1 answer

An enum not a structure; it is an integral type with a predefined set of values ​​(enumerator constants). It makes no sense to represent it using ctypes.Structure . You are 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) 
+5
source

Source: https://habr.com/ru/post/1481436/


All Articles