| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
|
| 13 |
|
| 14 |
|
| 15 |
|
| 16 |
|
| 17 |
""" |
| 18 |
pyudev._ctypeslib.utils |
| 19 |
======================= |
| 20 |
|
| 21 |
Utilities for loading ctypeslib. |
| 22 |
|
| 23 |
.. moduleauthor:: Anne Mulhern <[email protected]> |
| 24 |
""" |
| 25 |
|
| 26 |
|
| 27 |
from ctypes import CDLL |
| 28 |
from ctypes.util import find_library |
| 29 |
|
| 30 |
|
| 31 |
def load_ctypes_library(name, signatures, error_checkers): |
| 32 |
""" |
| 33 |
Load library ``name`` and return a :class:`ctypes.CDLL` object for it. |
| 34 |
|
| 35 |
:param str name: the library name |
| 36 |
:param signatures: signatures of methods |
| 37 |
:type signatures: dict of str * (tuple of (list of type) * type) |
| 38 |
:param error_checkers: error checkers for methods |
| 39 |
:type error_checkers: dict of str * ((int * ptr * arglist) -> int) |
| 40 |
|
| 41 |
The library has errno handling enabled. |
| 42 |
Important functions are given proper signatures and return types to support |
| 43 |
type checking and argument conversion. |
| 44 |
|
| 45 |
:returns: a loaded library |
| 46 |
:rtype: ctypes.CDLL |
| 47 |
:raises ImportError: if the library is not found |
| 48 |
""" |
| •49 |
if ".so" in name: |
| 50 |
library_name = name |
| 51 |
else: |
| 52 |
library_name = find_library(name) |
| 53 |
if not library_name: |
| 54 |
raise ImportError(f"No library named {name}") |
| 55 |
lib = CDLL(library_name, use_errno=True) |
| 56 |
|
| 57 |
for funcname, signature in signatures.items(): |
| 58 |
function = getattr(lib, funcname, None) |
| 59 |
if function: |
| 60 |
argtypes, restype = signature |
| 61 |
function.argtypes = argtypes |
| 62 |
function.restype = restype |
| 63 |
errorchecker = error_checkers.get(funcname) |
| 64 |
if errorchecker: |
| 65 |
function.errcheck = errorchecker |
| 66 |
return lib |