I’ve been working on a new Python binding for libSDL2 using cffi,
creatively called “pysdl2-cffi”. Documentation is at
https://pythonhosted.org/pysdl2-cffi/index.html . I’ve really been
enjoying using the great SDL2 library this way.
The binding uses cffi so it can be fast on PyPy, the JIT-compiled
Python implementation. On the programs I’ve tested it with the speedup
is can be from 2x - 10x faster. Programs that do a lot of computation
in Python are likely to benefit the most.
The binding preserves SDL2’s original argument names and doxygen
documentation so it is pleasing to discover interactively:
$ ipython
import sdl
sdl.init?
Definition: sdl.init(flags)
Docstring:
int SDL_Init(uint32_t)
This function initializes the subsystems specified by flags Unless the
SDL_INIT_NOPARACHUTE flag is set, it will install cleanup signal
handlers for some commonly ignored fatal signals (like SIGSEGV).
sdl.getPowerInfo?
Definition: sdl.getPowerInfo(secs=None, pct=None)
Docstring:
SDL_PowerState SDL_GetPowerInfo(int *, int *)
Get the current power supply details.
:param secs: Seconds of battery life left
…
The binding automatically converts primitive pointer types to optional
output parameters, returning them as tuples:
sdl.getPowerInfo()
(1, 7320, 49)
(This means sdl.POWERSTATE_ON_BATTERY, 7320 seconds remaining, 49% capacity)
The binding exposes structs as classes, and functions taking that
struct as a first argument as methods on those classes. Unlike typical
Python bindings, you can avoid unnecessary allocation by passing the
struct back into the functions that mutate it:
event = sdl.Event()
sdl.pollEvent(event) # or
event.pollEvent()
The binding converts most SDL errors to exceptions, not by checking
SDL_GetError() on every function call, but only by checking the return
value for -1, 0, or NULL depending on its documented error reporting
convention.
The binding is consistent as it is mostly generated from SDL2’s own C
function declarations.
SDL2, mixer, ttf, and image are wrapped.
(I noticed mixer does not share the same error reporting conventions
as the other SDL-family libraries…)
Hopefully some people will find pysdl2-cffi to be useful.
Thanks,
Daniel Holth