Accessing cffi enums

这一生的挚爱 提交于 2019-12-23 18:53:34

问题


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.



来源:https://stackoverflow.com/questions/27223489/accessing-cffi-enums

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!