Access to cffi enumerations

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 retrieved when called cdef

again. But how would I then like to access this enum in python without re-declaring it? Can't find references in the docs.

+3


source to share


3 answers


Use ffi.dlopen

and access the enumeration value by defining with the return value 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

      

+3


source


If you've wrapped the library, you can use the above:



import _wrappedlib

print _wrappedlib.lib.RANDOM

      

0


source


After the answer ffi.dlopen('c')

doesn't work anymore for Windows 7 and Python 3.7 but today I found that we can use any library instead 'c'

and it still works. It is recommended to use at https://bugs.python.org/issue23606ucrtbase.dll

, so we can do the following:

>>> ffi.cdef('#define MAX_PATH 260')
>>> ffi.dlopen('kernel32.dll').MAX_PATH
260

      

Another more complex way for enums is to use self.typeof('strategy').relements['RANDOM']

, but that doesn't work for #define

, so the above is better.

0


source







All Articles