spacepaste

  1.  
  2. ffi.cdef("""
  3. struct ev_io { ...; }
  4. struct my_io {
  5. ev_io io;
  6. void *handle;
  7. ...;
  8. };
  9. """)
  10. ffi.set_source("_example", """
  11. static int (*python_callback)(void *handle, int revents);
  12. static void (*python_handle_error)(void *handle);
  13. static void my_io_callback(struct ev_loop *loop, ev_io *io, int revents)
  14. {
  15. /* invoke 'self.callback()' */
  16. void *handle = ((struct my_io *)io)->handle;
  17. if (python_callback(handle, revents) < 0) {
  18. /* in case of exception, call 'self.loop.handle_error()' */
  19. python_handle_error(handle);
  20. }
  21. ... more code to stop the event, like _run_callback() does ...
  22. }
  23. """)
  24. # this is done globally:
  25. @ffi.callback("int(void *handle, int revents)", error=-1)
  26. def python_callback(handle, revents):
  27. watcher = ffi.from_handle(handle)
  28. watcher.callback(*watcher.args)
  29. return 0
  30. lib.python_callback = python_callback
  31. # then this is done in class io's __init__:
  32. class io(watcher):
  33. def __init__(self, ...):
  34. self._handle = ffi.new_handle(self)
  35. self._watcher = ffi.new("my_io *")
  36. self._watcher.handle = self._handle
  37. # give the same C-level callback function to all of them
  38. self._watcher_init(self._watcher, lib.my_io_callback)
  39.