Source

pysdl-cffi / sdl / internal.py

Full commit
from __future__ import (print_function, division, absolute_import)

from cffi import FFI
import traceback
import sys
import os

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

class SDLError(Exception):
    pass

_ffi = FFI()
_LIB = None

IS_DARWIN = sys.platform == 'darwin'
IS_WIN32 = sys.platform == 'win32'
IS_LINUX = sys.platform == 'linux2'
_THISDIR = os.path.abspath(os.path.dirname(__file__))  

def load_lib(cdefs):
    global _LIB
    libname = 'SDL2'
    if IS_WIN32:
        local_dl = os.path.join(_THISDIR, 'SDL2.dll')
    elif IS_LINUX:
        local_dl = os.path.join(_THISDIR, 'libSDL2.so')
    elif IS_DARWIN:
        local_dl = os.path.join(_THISDIR, 'libSDL2.dylib')
    else:
        local_dl = None
        
    if local_dl and os.path.isfile(local_dl):
        #print("using {0}".format(local_dl))
        libname = local_dl 
        
    #import time
    #t = time.time()
    _ffi.cdef(cdefs)
    #print("SDL cdefs loaded in {0}s".format(time.time() - t))
    try:
        _LIB = _ffi.dlopen(libname)
    except:
        print("ERROR: unable to import SDL2")
        traceback.print_exc()
    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