Search code examples
pythonpython-cffi

Accessing cffi enums


Suppose I define an enum under cffi:

from cffi import FFI
ffi = FFI()
ffi.cdef('typedef enum {RANDOM, IMMEDIATE, SEARCH} strategy;')

Now this can be easily accessed when calling cdef again. But how would I then like to access this enum in python, without re-declaring it? Can't find any mentions in the docs.


Solution

  • Use ffi.dlopen, and access the enum value by qualifying using the return value of the ffi.dlopen:

    >>> from cffi import FFI
    >>> ffi = FFI()
    >>> ffi.cdef('typedef enum {RANDOM, IMMEDIATE, SEARCH} strategy;')
    >>> c = ffi.dlopen('c')
    >>> c.RANDOM
    0
    >>> c.IMMEDIATE
    1
    >>> c.SEARCH
    2