36
36
from __future__ import (print_function, division, unicode_literals,
39
from ctypes import CDLL
40
from ctypes.util import find_library
39
41
from contextlib import contextmanager
44
def load_library(name, signatures=None):
46
Load the C library with the given ``name``.
48
``name`` is a string containing a generic library name (as for
49
:func:`ctypes.util.find_library`). If ``signatures`` is given, it must be
50
a dictionary with signatures of functions of the library, see
51
:func:`add_foreign_signatures` for details.
53
Return a :class:`ctypes.CDLL` wrapping the library. Raise
54
:exc:`~exceptions.ImportError`, if the library was not found.
56
library_name = find_library(name)
58
raise ImportError('No library named {0}'.format(name))
59
library = CDLL(library_name)
61
library = add_foreign_signatures(library, signatures)
42
65
def add_foreign_signatures(library, signatures):
44
Add ``signatures`` of a foreign ``library`` to the symbols defined in
67
Add ``signatures`` of a foreign ``library`` to the symbols defined in this
47
``library`` is a :class:`~ctypes.CDLL` object, wrapping a foreign
48
library. ``signatures`` is a dictionary, which specifies signatures for
49
symbols defined in this library. It maps the name of a function to a
50
three element tuple ``(argument_types, return_type, error_checker)``.
51
``argument_types`` is a list of argument types (see
52
:attr:`~ctypes._FuncPtr.argtypes`), ``return_type`` is the return type
53
(see :attr:`~ctypes._FuncPtr.restype`) and ``error_checker`` is a
54
function used as error checker (see :attr:``~ctypes._FuncPtr.errcheck`).
55
``error_checker`` may be ``None``, in which case no error checking
70
``library`` is a :class:`~ctypes.CDLL` object, wrapping a foreign library.
71
``signatures`` is a dictionary, which specifies signatures for symbols
72
defined in this library. It maps the name of a function to a two or three
73
component tuple ``(argument_types, return_type, error_checker)``, where
74
``error_checker`` is optional and can be omitted. ``argument_types`` is a
75
list of argument types (see :attr:`~ctypes._FuncPtr.argtypes`),
76
``return_type`` is the return type (see :attr:`~ctypes._FuncPtr.restype`)
77
and ``error_checker`` is a function used as error checker (see
78
:attr:``~ctypes._FuncPtr.errcheck`). ``error_checker`` may be ``None``, in
79
which case no error checking function is defined.
58
81
Return the ``library`` object again.
60
83
for name, signature in signatures.iteritems():
61
84
function = getattr(library, name)
62
argument_types, return_type, error_checker = signature
85
if len(signature) == 2:
86
argument_types, return_type = signature
89
argument_types, return_type, error_checker = signature
63
90
function.argtypes = argument_types
64
91
function.restype = return_type