[Pyrex] lots of callback functions

Robert Bradshaw robertwb at math.washington.edu
Sat May 30 17:50:12 CEST 2009


On May 29, 2009, at 6:28 AM, horace wrote:

> hi,
>
> i have figured out how to wrap callback functions but i have a  
> special case which is a bit cumbersome.
>
> i have to wrap a struct which contains events for every key on the  
> keyboard:
>
> cdef extern from "engine.h":
>     ctypedef struct ENGINE_VARIABLES:
>         EVENT *on_esc
>         EVENT *on_f1
>         EVENT *on_f2
>         EVENT *on_f3
>         # ... events for the rest of the keyboard
>
> of course i could write a predefined cdef callback for each single  
> event, add a variable for storing the user definable python  
> callback (which gets called from the cdef callback) for each single  
> event and so on.
>
> but maybe someone has an idea how this could be done more elegantly  
> without so much writing?


This sounds like a cumbersome interface, but you're probably not in a  
position to change engine.h. I take it EVENT here is a function type?  
Does it have any arguments? If not, your method sounds like the only  
option (perhaps you could have have a register_callback method that  
would take as input a enum for each key and store it in a dict). E.g.

cdef dict py_callbacks = {}

cdef enum event_keys:
     esc
     f1
     f2
     ...

cdef esc_callback():
     try:
         py_callbacks[esc]()
     except KeyError: # if callbacks are scarce, maybe you should do  
a haskey instead of catching KeyErrors
         pass

cdef f1_callback():
     ...

def register_callback(key, func):
     py_callbacks[key] = func

If it were me, I'd auto-generate this file.

- Robert




More information about the Pyrex mailing list