-->

Accessing cffi enums

2019-07-03 14:50发布

问题:

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.

回答1:

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


回答2:

If you have wrapped over a library you can use the same above as following :

import _wrappedlib

print _wrappedlib.lib.RANDOM


回答3:

Following @falsetru's answer, ffi.dlopen('c') doesn't work anymore for Windows 7 and Python 3.7, but I discovered today that we can use any library instead of 'c' and it still works. The recommended one at https://bugs.python.org/issue23606 is to use ucrtbase.dll, so we can do:

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

Another more complicated way for enums is to use self.typeof('strategy').relements['RANDOM'], but this does not work for #defines, so the above way is better.