It is possible to load a library using >>> lib = ctypes.cdll[ ] # doctest: +SKIP But there are cross-platform considerations, such as library file extensions, plus the fact Windows will just load the first library it finds with that name. Num
(libname, loader_path)
| 88 | |
| 89 | # Adapted from Albert Strasheim |
| 90 | def load_library(libname, loader_path): |
| 91 | """ |
| 92 | It is possible to load a library using |
| 93 | |
| 94 | >>> lib = ctypes.cdll[<full_path_name>] # doctest: +SKIP |
| 95 | |
| 96 | But there are cross-platform considerations, such as library file extensions, |
| 97 | plus the fact Windows will just load the first library it finds with that name. |
| 98 | NumPy supplies the load_library function as a convenience. |
| 99 | |
| 100 | .. versionchanged:: 1.20.0 |
| 101 | Allow libname and loader_path to take any |
| 102 | :term:`python:path-like object`. |
| 103 | |
| 104 | Parameters |
| 105 | ---------- |
| 106 | libname : path-like |
| 107 | Name of the library, which can have 'lib' as a prefix, |
| 108 | but without an extension. |
| 109 | loader_path : path-like |
| 110 | Where the library can be found. |
| 111 | |
| 112 | Returns |
| 113 | ------- |
| 114 | ctypes.cdll[libpath] : library object |
| 115 | A ctypes library object |
| 116 | |
| 117 | Raises |
| 118 | ------ |
| 119 | OSError |
| 120 | If there is no library with the expected extension, or the |
| 121 | library is defective and cannot be loaded. |
| 122 | """ |
| 123 | # Convert path-like objects into strings |
| 124 | libname = os.fsdecode(libname) |
| 125 | loader_path = os.fsdecode(loader_path) |
| 126 | |
| 127 | ext = os.path.splitext(libname)[1] |
| 128 | if not ext: |
| 129 | import sys |
| 130 | import sysconfig |
| 131 | # Try to load library with platform-specific name, otherwise |
| 132 | # default to libname.[so|dll|dylib]. Sometimes, these files are |
| 133 | # built erroneously on non-linux platforms. |
| 134 | base_ext = ".so" |
| 135 | if sys.platform.startswith("darwin"): |
| 136 | base_ext = ".dylib" |
| 137 | elif sys.platform.startswith("win"): |
| 138 | base_ext = ".dll" |
| 139 | libname_ext = [libname + base_ext] |
| 140 | so_ext = sysconfig.get_config_var("EXT_SUFFIX") |
| 141 | if not so_ext == base_ext: |
| 142 | libname_ext.insert(0, libname + so_ext) |
| 143 | else: |
| 144 | libname_ext = [libname] |
| 145 | |
| 146 | loader_path = os.path.abspath(loader_path) |
| 147 | if not os.path.isdir(loader_path): |