Accessing cffi enums

2019-07-03 14:28发布

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.

3条回答
我欲成王,谁敢阻挡
2楼-- · 2019-07-03 15:11

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

import _wrappedlib

print _wrappedlib.lib.RANDOM
查看更多
一夜七次
3楼-- · 2019-07-03 15:18

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.

查看更多
老娘就宠你
4楼-- · 2019-07-03 15:32

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
查看更多
登录 后发表回答