1

I would like to make one of the fields of my ctypes.Structure an enum. This post suggests adding a from_param classmethod to the enum class, but claims that this isn't enough for a custom ctypes.Structure. I've also tried inheriting from both enum.IntEnum and ctypes.c_uint but that results a metaclass conflict. Here is approximately what I want:

class MyEnum(enum.IntEnum):
    A = 0
    B = 1

class MyStruct(ctypes.Structure):
    _fields_ = [
        ('my_enum', MyEnum),
        ...
    ]
Vlad Firoiu
  • 987
  • 1
  • 8
  • 17
  • 1
    Have you seen [this question](http://stackoverflow.com/q/27199479/208880)? – Ethan Furman Apr 27 '16 at 00:06
  • 1
    I had not seen that question, but I've tried the approach given in that answer and it gives me `TypeError: second item in _fields_ tuple (index 0) must be a C type` even if I subclass the `CEnum` type they create. – Vlad Firoiu Apr 27 '16 at 00:21
  • The `from_param` hook is called to convert a function argument to a type that ctypes can use directly. It doesn't enable using an arbitrary type in a C aggregate type (i.e. `ctypes.Array`, `ctypes.Structure`, or `ctypes.Union`) or as the `_type_` of a `ctypes._Pointer`. – Eryk Sun Apr 27 '16 at 03:15
  • You can subclass `ctypes.c_int` to create an enum class that overrides `__new__` to restrict instantiation and implements the class methods `_check_retval_` and `from_param` to restrict the value for a given result or argument. However, there's no hook to restrict the value to get from or set to an aggregate type or dereferenced pointer, not without using ctypes to hack itself to implement a custom `getfunc` and `setfunc` for the type. – Eryk Sun Apr 27 '16 at 03:18

0 Answers0