fearless_fool
fearless_fool

Reputation: 35229

Using Python cffi for introspection

I'm contemplating using Python's cffi module as part of a Remote Procedure Call package: you create a single <mymodule>.h file and use cffi to generate the JSON encoders and decoders between the two endpoints.

To do this, I'd use cffi to parse the typedefs, the structs and the function signatures, which I'd then use to create the encoders and decoders for the JSON code.

I can see how to get cffi's internal model of a typedef, e.g.:

>>> from cffi import FFI
>>> import pprint
>>> ffi = FFI()
>>> ffi.cdef("""
typedef enum { LED_HEAT, LED_FAN} led_id_t;
void set_led(led_id_t led_id, bool on);
""")
>>> led_id_type = ffi.typeof('led_id_t')
>>> led_id_type.elements
{1: 'LED_FAN', 0: 'LED_HEAT'}

Question: I know that cffi has a model for the signature of the set_led() function. What cffi functions give me access to that model?

Update

By groveling over the cffi sources, I see that I can do the following:

>>> x = ffi._parser._declarations['function set_led']
>>> x
(<void(*)(led_id_t, _Bool)>, 0)
>>> type(x[0])
<class 'cffi.model.FunctionPtrType'>
>>> x[0].args
(<led_id_t>, <_Bool>)
>>> type(x[0][0])
<class 'cffi.model.EnumType'>

... which gets me pretty much what I want. Is there a published API for going that (or at least something that doesn't dig so deeply into the internals)?

Upvotes: 1

Views: 104

Answers (0)

Related Questions