pysdl-cffi / sdl / internal.py

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_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')
    else:
        local_dl = None
        
    if local_dl and os.path.isfile(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
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.