Debian Codegraph @

src/pyudev/_ctypeslib/utils.py

raw symbols ◀ ▶ SCIP
1 Debian patch touch this file
1 # -*- coding: utf-8 -*-
2 # Copyright (C) 2013 Sebastian Wiesner <[email protected]>
3
4 # This library is free software; you can redistribute it and/or modify it
5 # under the terms of the GNU Lesser General Public License as published by the
6 # Free Software Foundation; either version 2.1 of the License, or (at your
7 # option) any later version.
8
9 # This library is distributed in the hope that it will be useful, but WITHOUT
10 # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11 # FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
12 # for more details.
13
14 # You should have received a copy of the GNU Lesser General Public License
15 # along with this library; if not, write to the Free Software Foundation,
16 # Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
17 """
18 pyudev._ctypeslib.utils
19 =======================
20
21 Utilities for loading ctypeslib.
22
23 .. moduleauthor:: Anne Mulhern <[email protected]>
24 """
25
26 # isort: STDLIB
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 # Add function signatures
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