midgard.dev.library

Python wrapper around C-libraries

Description:

Loads a C-library. If a library is missing, a mock library is returned. If this mock is used for anything, a warning will be printed. This is done to avoid dependencies to all the C/C++-libraries for Python programs only using some of them.

SimpleMock

SimpleMock(name, raise_error=True)

Class that can stand in for any other object

The SimpleMock is used to stand in for any library that can not be imported. The mock object simply returns itself whenever it is called, or any attributes are looked up on the object. This is done, to avoid ImportErrors when a library is imported, but never used (typically because a plugin is loaded but never called).

Instead the ImportError is raised when the SimpleMock is used in any way. The ImportError will only be raised once for any SimpleMock-object (which is only important if the ImportError is caught and the program carries on).

load_name()

load_name(library_name, func_specs=None, name_patterns=None)

Load the given shared C-library

See load_path for an explanation of the func_specs and name_patterns-arguments.

Args:

library_name (String): The name of the library. func_specs (Dict): Specification of types in lib (see load_path). name_patterns (List): Name mangling patterns (see load_path).

Returns:

ctypes.CDLL: Representation of the shared library.

load_path()

load_path(library_path, func_specs=None, name_patterns=None)

Load the given shared C-library

The optional func_specs-dictionary can be used to specify argument and return types of functions in the library (see the ctypes documentation for information about argtypes and restype). The dictionary should be on the form::

func_spec = {'func_1': dict(func_name='name_of_func_1_in_lib',
                            argtypes=[ ... argtypes of func_1 ... ],
                            restype=... restype of func_1 ...),
             'func_2': ...
            }

If the library is not found, a mock library is returned instead. The mock library will print a warning if it is used.

For some libraries, name mangling is used and this might be different depending on operating system and how the library is compiled. For instance, in a Fortran library the function Test might be represented as __Test on a Windows system and test_ (with lower-case t) on a Linux system. This can be handled by providing a list of possible patterns. The above example can be handled by::

name_patterns = ('__{func_name}', '{func_name_lower}_')

In this case, each function in func_specs is looked up by testing each pattern in turn until a match is found.

Args:

library_path (String): The path to the library. func_specs (Dict): Specification of types in library (see above). name_patterns (List): Name mangling patterns (see above).

Returns:

ctypes.CDLL: Representation of the shared library.