Source

pysdl-cffi / sdl / internal.py

Full commit

from cffi import FFI

__all__ = [
    '_ffi',
    'load_lib',
    'lookup',
    'check_error',
    'guard',
    'SDLError',
]

class SDLError(Exception):
    pass

_ffi = FFI()
_LIB = None

def load_lib(cdefs):
    global _LIB
    import time
    t = time.time()
    _ffi.cdef(cdefs)
    print("SDL cdefs loaded in {0}s".format(time.time() - t))
    _LIB = _ffi.dlopen('SDL2')
    return _LIB

def wrapstr(result):
    if result:
        return _ffi.string(result)
    return None

def wrap_retstr(func):
    def wrapper(*argv):
        return wrapstr(func(*argv))
    return wrapper

def lookup(name):
    if hasattr(_LIB, name):
        return getattr(_LIB, name)
    print("SDL warning: function",name,"missing.")
    return None 
    
def check_error():
    error = _ffi.string(_LIB.SDL_GetError())
    if error:
        _LIB.SDL_ClearError()
        raise SDLError, error

def guard(func):
    if not func:
        return None    
    name = repr(func)
    def newfunc(*args):
        result = func(*args)
        check_error()
        return result
    newfunc.func_name = name
    newfunc.__doc__ = func.__doc__
    return newfunc