我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用ctypes.util.find_library()。
def find_yajl_ctypes(required): ''' Finds and loads yajl shared object of the required major version (1, 2, ...) using ctypes. ''' # Importing ``ctypes`` should be in scope of this function to prevent failure # of `backends`` package load in a runtime where ``ctypes`` is not available. # Example of such environment is Google App Engine (GAE). from ctypes import util, cdll so_name = util.find_library('yajl') if so_name is None: raise YAJLImportError('YAJL shared object not found.') yajl = cdll.LoadLibrary(so_name) require_version(yajl.yajl_version(), required) return yajl
def ntp_adjtime(): retval = None try: libc = cdll.LoadLibrary(find_library("c")) timex = TimexStruct() p_timex = pointer(timex) libc.ntp_adjtime(p_timex) retval = p_timex.contents except Exception as e: return None return retval # ---------------------------
def test_load_library(self): self.assertIsNotNone(libc_name) if is_resource_enabled("printing"): print find_library("kernel32") print find_library("user32") if os.name == "nt": windll.kernel32.GetModuleHandleW windll["kernel32"].GetModuleHandleW windll.LoadLibrary("kernel32").GetModuleHandleW WinDLL("kernel32").GetModuleHandleW elif os.name == "ce": windll.coredll.GetModuleHandleW windll["coredll"].GetModuleHandleW windll.LoadLibrary("coredll").GetModuleHandleW WinDLL("coredll").GetModuleHandleW
def _libnccl(): global nccl_2_0 global lib global status_codes global nccl_types if lib is None: lib = ctypes.pydll.LoadLibrary(find_library('nccl')) if hasattr(lib, 'ncclCommDestroy'): lib.ncclCommDestroy.restype = None else: lib = None if hasattr(lib, 'ncclGroupStart'): nccl_2_0 = True status_codes = status_codes_2_0 nccl_types = nccl_types_2_0 return lib
def _e_path_possibilities(): """Generator yielding possible locations of the enchant library.""" # Allow it to be overridden using an environment variable. yield os.environ.get("PYENCHANT_LIBRARY_PATH") # For linuxish systems, allow default soname lookup a chance to succeed. if sys.platform not in ("win32", "darwin"): yield "libenchant.so.1.6.0" yield "libenchant.so.1" yield "libenchant.so" # See if ctypes can find the library for us, under various names. yield find_library("enchant") yield find_library("libenchant") yield find_library("libenchant-1") # Special-case handling for enchant installed by macports. if sys.platform == 'darwin': yield "/opt/local/lib/libenchant.dylib" # On win32 we ship a bundled version of the enchant DLLs. # Use them if they're present.
def find_cuda(): cuda_home = os.getenv('CUDA_HOME', '/usr/local/cuda') if not os.path.exists(cuda_home): # We use nvcc path on Linux and cudart path on macOS osname = platform.system() if osname == 'Linux': cuda_path = find_nvcc() else: cudart_path = find_library('cudart') if cudart_path is not None: cuda_path = os.path.dirname(cudart_path) else: cuda_path = None if cuda_path is not None: cuda_home = os.path.dirname(cuda_path) else: cuda_home = None return cuda_home is not None # Build-specific dependencies.
def test_load_library(self): self.assertFalse(libc_name is None) if is_resource_enabled("printing"): print(find_library("kernel32")) print(find_library("user32")) if os.name == "nt": windll.kernel32.GetModuleHandleW windll["kernel32"].GetModuleHandleW windll.LoadLibrary("kernel32").GetModuleHandleW WinDLL("kernel32").GetModuleHandleW elif os.name == "ce": windll.coredll.GetModuleHandleW windll["coredll"].GetModuleHandleW windll.LoadLibrary("coredll").GetModuleHandleW WinDLL("coredll").GetModuleHandleW
def load_dll(libname, fallbacks=None): lib = find_library(libname) if lib is not None: return CDLL(lib) else: if fallbacks is not None: for name in fallbacks: try: return CDLL(name) except OSError: # move on to the next fallback pass # the end raise OSError( "Could not find library %s or load any of its variants %s" % ( libname, fallbacks or []))
def __init__(self): v_posix.PosixMixin.__init__(self) v_posix.PtraceMixin.__init__(self) self.libc = ctypes.CDLL(c_util.find_library('c')) self.myport = self.libc.mach_task_self() self.libc.mach_port_allocate.argtypes = [ipc_space_t, mach_port_right_t, ctypes.POINTER(mach_port_name_t)] self.libc.mach_port_allocate.restype = kern_return_t self.libc.mach_vm_read.argtypes = [ mach_port_t, size_t, size_t, ctypes.POINTER(ctypes.c_void_p), ctypes.POINTER(ctypes.c_uint32)] self.libc.mach_vm_read.restype = kern_return_t self.libc.ptrace.restype = ctypes.c_int self.libc.ptrace.argtypes = [ctypes.c_int, ctypes.c_uint32, ctypes.c_size_t, ctypes.c_int] machhelp_path = os.path.join(darwindir, 'machhelper.dylib') self.machhelper = ctypes.CDLL(machhelp_path) self.machhelper.platformPs.restype = ctypes.POINTER(ProcessListEntry) self.useptrace = False self.portset = self.newMachPort(MACH_PORT_RIGHT_PORT_SET) self.excport = self.newMachRWPort() self.addPortToSet(self.excport)
def ptrace(code, pid, addr, data): """ The contents of this call are basically cleanly passed to the libc implementation of ptrace. """ global libc if not libc: if os.getenv('ANDROID_ROOT'): cloc = '/system/lib/libc.so' else: cloc = cutil.find_library("c") if not cloc: raise Exception("ERROR: can't find C library on posix system!") libc = CDLL(cloc) libc.ptrace.restype = c_size_t libc.ptrace.argtypes = [c_int, c_uint32, c_size_t, c_size_t] return libc.ptrace(code, pid, c_size_t(addr), c_size_t(data))
def test_load_library(self): self.assertIsNotNone(libc_name) if test.support.verbose: print(find_library("kernel32")) print(find_library("user32")) if os.name == "nt": windll.kernel32.GetModuleHandleW windll["kernel32"].GetModuleHandleW windll.LoadLibrary("kernel32").GetModuleHandleW WinDLL("kernel32").GetModuleHandleW elif os.name == "ce": windll.coredll.GetModuleHandleW windll["coredll"].GetModuleHandleW windll.LoadLibrary("coredll").GetModuleHandleW WinDLL("coredll").GetModuleHandleW
def test_load_library(self): self.assertFalse(libc_name is None) if is_resource_enabled("printing"): print find_library("kernel32") print find_library("user32") if os.name == "nt": windll.kernel32.GetModuleHandleW windll["kernel32"].GetModuleHandleW windll.LoadLibrary("kernel32").GetModuleHandleW WinDLL("kernel32").GetModuleHandleW elif os.name == "ce": windll.coredll.GetModuleHandleW windll["coredll"].GetModuleHandleW windll.LoadLibrary("coredll").GetModuleHandleW WinDLL("coredll").GetModuleHandleW
def _load_or_error(name): path = util.find_library(name) if path is not None: return CDLL(path) # On iOS (and probably also watchOS and tvOS), ctypes.util.find_library doesn't work and always returns None. # This is because the sandbox hides all system libraries from the filesystem and pretends they don't exist. # However they can still be loaded if the path is known, so we try to load the library from a few known locations. for loc in _lib_path: try: return CDLL(os.path.join(loc, "lib" + name + ".dylib")) except OSError: pass for loc in _framework_path: try: return CDLL(os.path.join(loc, name + ".framework", name)) except OSError: pass raise ValueError("Library {!r} not found".format(name))
def psloadlib(name): """ Loads driver library :param name: driver name :type name: str :returns: ctypes reference to the library :rtype: object """ result = None try: if sys.platform == 'win32': result = ctypes.WinDLL(find_library(name)) else: result = cdll.LoadLibrary(find_library(name)) except OSError as ex: print name, "import(%d): Library not found" % sys.exc_info()[-1].tb_lineno return result
def initialize(path=None): """Load `libeXosip2` into this Python library :param str path: `libeXosip2` SO/DLL path, `default` is `None`. When `None` or empty string, the function will try to find and load so/dll by :data:`DLL_NAME` """ _logger.info('initialize: >>> path=%s', path) if globs.libexosip2: raise RuntimeError('library eXosip2 already loaded') if not path: _logger.debug('initialize: find_library "%s"', DLL_NAME) path = find_library(DLL_NAME) if not path: raise RuntimeError('Failed to find library {}'.format(DLL_NAME)) _logger.debug('initialize: CDLL %s', path) globs.libexosip2 = CDLL(path) if not globs.libexosip2: raise RuntimeError('Failed to load library {}'.format(path)) _logger.debug('initialize: libexosip2=%s', globs.libexosip2) for cls in globs.func_classes: cls.bind() _logger.info('initialize: <<<')
def zerome(string): # find the header size with a dummy string dummy = "header finder" header = ctypes.string_at(id(dummy), sys.getsizeof(dummy)).find(dummy) location = id(string) + header size = sys.getsizeof(string) - header if platform.system() == 'Windows': memset = ctypes.cdll.msvcrt.memset else: libc = find_library('c') memset = ctypes.CDLL(libc).memset # For OS X, the above should work, but if it doesn't: # memset = ctypes.CDLL('libc.dylib').memset print "Clearing 0x%08x size %i bytes" % (location, size) memset(location, 0, size) #string still with us? print ctypes.string_at(location, size)
def __init__(self): ''' MacOS X initialisations. ''' coregraphics = find_library('CoreGraphics') if not coregraphics: raise ScreenshotError('No CoreGraphics library found.') self.core = cdll.LoadLibrary(coregraphics) self._set_argtypes() self._set_restypes()
def _init(): """ Loads the shared library through ctypes and returns a library L{ctypes.CDLL} instance """ return ctypes.cdll.LoadLibrary(find_library('magic'))
def _importLibrary(self): piLibName= 'pi_pi_gcs2' pilib= find_library(piLibName) if pilib is None: raise PIException("Library %s not found" % piLibName) self._lib= ctypes.CDLL(pilib)
def setUp(self): self.libc= ctypes.CDLL(find_library("c")) self.libm= ctypes.CDLL(find_library("m"))
def load_libsodium(): global loaded, libsodium, buf from ctypes.util import find_library for p in ('sodium',): libsodium_path = find_library(p) if libsodium_path: break else: raise Exception('libsodium not found') logging.info('loading libsodium from %s', libsodium_path) libsodium = CDLL(libsodium_path) libsodium.sodium_init.restype = c_int libsodium.crypto_stream_salsa20_xor_ic.restype = c_int libsodium.crypto_stream_salsa20_xor_ic.argtypes = (c_void_p, c_char_p, c_ulonglong, c_char_p, c_ulonglong, c_char_p) libsodium.crypto_stream_chacha20_xor_ic.restype = c_int libsodium.crypto_stream_chacha20_xor_ic.argtypes = (c_void_p, c_char_p, c_ulonglong, c_char_p, c_ulonglong, c_char_p) libsodium.sodium_init() buf = create_string_buffer(buf_size) loaded = True
def load_openssl(): global loaded, libcrypto, buf from ctypes.util import find_library for p in ('crypto', 'eay32', 'libeay32'): libcrypto_path = find_library(p) if libcrypto_path: break else: raise Exception('libcrypto(OpenSSL) not found') logging.info('loading libcrypto from %s', libcrypto_path) libcrypto = CDLL(libcrypto_path) libcrypto.EVP_get_cipherbyname.restype = c_void_p libcrypto.EVP_CIPHER_CTX_new.restype = c_void_p libcrypto.EVP_CipherInit_ex.argtypes = (c_void_p, c_void_p, c_char_p, c_char_p, c_char_p, c_int) libcrypto.EVP_CipherUpdate.argtypes = (c_void_p, c_void_p, c_void_p, c_char_p, c_int) libcrypto.EVP_CIPHER_CTX_cleanup.argtypes = (c_void_p,) libcrypto.EVP_CIPHER_CTX_free.argtypes = (c_void_p,) if hasattr(libcrypto, 'OpenSSL_add_all_ciphers'): libcrypto.OpenSSL_add_all_ciphers() buf = create_string_buffer(buf_size) loaded = True
def test_find(self): for name in ("c", "m"): lib = find_library(name) if lib: cdll.LoadLibrary(lib) CDLL(lib)
def test_open(self): libc_name = find_library("c") if libc_name is None: raise unittest.SkipTest("Unable to find C library") libc = CDLL(libc_name, use_errno=True) if os.name == "nt": libc_open = libc._open else: libc_open = libc.open libc_open.argtypes = c_char_p, c_int self.assertEqual(libc_open("", 0), -1) self.assertEqual(get_errno(), errno.ENOENT) self.assertEqual(set_errno(32), errno.ENOENT) self.assertEqual(get_errno(), 32) if threading: def _worker(): set_errno(0) libc = CDLL(libc_name, use_errno=False) if os.name == "nt": libc_open = libc._open else: libc_open = libc.open libc_open.argtypes = c_char_p, c_int self.assertEqual(libc_open("", 0), -1) self.assertEqual(get_errno(), 0) t = threading.Thread(target=_worker) t.start() t.join() self.assertEqual(get_errno(), 32) set_errno(0)
def test_issue_8959_a(self): from ctypes.util import find_library libc_path = find_library("c") if not libc_path: self.skipTest('could not find libc') libc = CDLL(libc_path) @CFUNCTYPE(c_int, POINTER(c_int), POINTER(c_int)) def cmp_func(a, b): return a[0] - b[0] array = (c_int * 5)(5, 1, 99, 7, 33) libc.qsort(array, len(array), sizeof(c_int), cmp_func) self.assertEqual(array[:], [1, 5, 7, 33, 99])
def __init__(self, sparcli): self.sparcli = sparcli self.voice = {} # Start OPUS if not loaded if not opus.is_loaded(): opus.load_opus(find_library('opus')) # Load what VCs it's already in for i in self.sparcli.servers: # Set up a nice dictionary for storage of information voiceClientInServer = self.sparcli.voice_client_in(i) self.voice[i] = ServerVoice(bot=self.sparcli, server=i, voiceClient=voiceClientInServer)
def load_inotify(): ''' Initialize the inotify library ''' global _inotify if _inotify is None: if hasattr(sys, 'getwindowsversion'): # On windows abort before loading the C library. Windows has # multiple, incompatible C runtimes, and we have no way of knowing # if the one chosen by ctypes is compatible with the currently # loaded one. raise INotifyError('INotify not available on windows') if sys.platform == 'darwin': raise INotifyError('INotify not available on OS X') if not hasattr(ctypes, 'c_ssize_t'): raise INotifyError('You need python >= 2.7 to use inotify') name = find_library('c') if not name: raise INotifyError('Cannot find C library') libc = ctypes.CDLL(name, use_errno=True) for function in ('inotify_add_watch', 'inotify_init1', 'inotify_rm_watch'): if not hasattr(libc, function): raise INotifyError('libc is too old') # inotify_init1() prototype = ctypes.CFUNCTYPE(ctypes.c_int, ctypes.c_int, use_errno=True) init1 = prototype(('inotify_init1', libc), ((1, 'flags', 0),)) # inotify_add_watch() prototype = ctypes.CFUNCTYPE(ctypes.c_int, ctypes.c_int, ctypes.c_char_p, ctypes.c_uint32, use_errno=True) add_watch = prototype(('inotify_add_watch', libc), ( (1, 'fd'), (1, 'pathname'), (1, 'mask'))) # inotify_rm_watch() prototype = ctypes.CFUNCTYPE(ctypes.c_int, ctypes.c_int, ctypes.c_int, use_errno=True) rm_watch = prototype(('inotify_rm_watch', libc), ( (1, 'fd'), (1, 'wd'))) # read() prototype = ctypes.CFUNCTYPE(ctypes.c_ssize_t, ctypes.c_int, ctypes.c_void_p, ctypes.c_size_t, use_errno=True) read = prototype(('read', libc), ( (1, 'fd'), (1, 'buf'), (1, 'count'))) _inotify = (init1, add_watch, rm_watch, read) return _inotify
def load_openssl(): global loaded, libcrypto, buf from ctypes.util import find_library for p in ('crypto', 'eay32', 'libeay32'): libcrypto_path = find_library(p) if libcrypto_path: break else: raise Exception('libcrypto(OpenSSL) not found') xlog.info('loading libcrypto from %s', libcrypto_path) libcrypto = CDLL(libcrypto_path) libcrypto.EVP_get_cipherbyname.restype = c_void_p libcrypto.EVP_CIPHER_CTX_new.restype = c_void_p libcrypto.EVP_CipherInit_ex.argtypes = (c_void_p, c_void_p, c_char_p, c_char_p, c_char_p, c_int) libcrypto.EVP_CipherUpdate.argtypes = (c_void_p, c_void_p, c_void_p, c_char_p, c_int) libcrypto.EVP_CIPHER_CTX_cleanup.argtypes = (c_void_p,) libcrypto.EVP_CIPHER_CTX_free.argtypes = (c_void_p,) if hasattr(libcrypto, 'OpenSSL_add_all_ciphers'): libcrypto.OpenSSL_add_all_ciphers() buf = create_string_buffer(buf_size) loaded = True
def loadOpenSSL(): global OpenSSL from os import path, environ from ctypes.util import find_library libdir = [] if getattr(sys,'frozen', None): if 'darwin' in sys.platform: libdir.extend([ path.join(environ['RESOURCEPATH'], '..', 'Frameworks','libcrypto.dylib'), path.join(environ['RESOURCEPATH'], '..', 'Frameworks','libcrypto.1.0.0.dylib') ]) elif 'win32' in sys.platform or 'win64' in sys.platform: libdir.append(path.join(sys._MEIPASS, 'libeay32.dll')) else: libdir.extend([ path.join(sys._MEIPASS, 'libcrypto.so'), path.join(sys._MEIPASS, 'libssl.so'), path.join(sys._MEIPASS, 'libcrypto.so.1.0.0'), path.join(sys._MEIPASS, 'libssl.so.1.0.0'), ]) if 'darwin' in sys.platform: libdir.extend(['libcrypto.dylib', '/usr/local/opt/openssl/lib/libcrypto.dylib']) elif 'win32' in sys.platform or 'win64' in sys.platform: libdir.append('libeay32.dll') else: libdir.append('libcrypto.so') libdir.append('libssl.so') if 'linux' in sys.platform or 'darwin' in sys.platform or 'freebsd' in sys.platform: libdir.append(find_library('ssl')) elif 'win32' in sys.platform or 'win64' in sys.platform: libdir.append(find_library('libeay32')) for library in libdir: try: OpenSSL = _OpenSSL(library) return except: pass raise Exception("Couldn't find and load the OpenSSL library. You must install it.")
def __init__(self, role, verbose=True, lib_name='libiperf.so.0'): """Initialise the iperf shared library :param role: 'c' = client; 's' = server :param verbose: enable verbose output :param lib_name: The libiperf name providing the API to iperf3 """ # TODO use find_library to find the best library try: self.lib = cdll.LoadLibrary(lib_name) except OSError: raise OSError('Could not find shared library {0}. Is iperf3 installed?'.format(lib_name)) # The test C struct iperf_test self._test = self._new() self.defaults() # stdout/strerr redirection variables self._stdout_fd = os.dup(1) self._stderr_fd = os.dup(2) self._pipe_out, self._pipe_in = os.pipe() # no need for pipe write # Generic test settings self.role = role self.json_output = True self.verbose = verbose
def check_tk_availability(): """Check that Tk is installed and available.""" global _tk_unavailable if _tk_unavailable is None: _tk_unavailable = False if sys.platform == 'darwin': # The Aqua Tk implementations on OS X can abort the process if # being called in an environment where a window server connection # cannot be made, for instance when invoked by a buildbot or ssh # process not running under the same user id as the current console # user. To avoid that, raise an exception if the window manager # connection is not available. from ctypes import cdll, c_int, pointer, Structure from ctypes.util import find_library app_services = cdll.LoadLibrary(find_library("ApplicationServices")) if app_services.CGMainDisplayID() == 0: _tk_unavailable = "cannot run without OS X window manager" else: class ProcessSerialNumber(Structure): _fields_ = [("highLongOfPSN", c_int), ("lowLongOfPSN", c_int)] psn = ProcessSerialNumber() psn_p = pointer(psn) if ( (app_services.GetCurrentProcess(psn_p) < 0) or (app_services.SetFrontProcess(psn_p) < 0) ): _tk_unavailable = "cannot run without OS X gui process" else: # not OS X import tkinter try: tkinter.Button() except tkinter.TclError as msg: # assuming tk is not available _tk_unavailable = "tk not available: %s" % msg if _tk_unavailable: raise unittest.SkipTest(_tk_unavailable) return
def test_open(self): libc_name = find_library("c") if libc_name is None: raise unittest.SkipTest("Unable to find C library") libc = CDLL(libc_name, use_errno=True) if os.name == "nt": libc_open = libc._open else: libc_open = libc.open libc_open.argtypes = c_char_p, c_int self.assertEqual(libc_open(b"", 0), -1) self.assertEqual(get_errno(), errno.ENOENT) self.assertEqual(set_errno(32), errno.ENOENT) self.assertEqual(get_errno(), 32) if threading: def _worker(): set_errno(0) libc = CDLL(libc_name, use_errno=False) if os.name == "nt": libc_open = libc._open else: libc_open = libc.open libc_open.argtypes = c_char_p, c_int self.assertEqual(libc_open(b"", 0), -1) self.assertEqual(get_errno(), 0) t = threading.Thread(target=_worker) t.start() t.join() self.assertEqual(get_errno(), 32) set_errno(0)
def test_issue_8959_a(self): from ctypes.util import find_library libc_path = find_library("c") if not libc_path: return # cannot test libc = CDLL(libc_path) @CFUNCTYPE(c_int, POINTER(c_int), POINTER(c_int)) def cmp_func(a, b): return a[0] - b[0] array = (c_int * 5)(5, 1, 99, 7, 33) libc.qsort(array, len(array), sizeof(c_int), cmp_func) self.assertEqual(array[:], [1, 5, 7, 33, 99])
def __init__(self, bot): self.bot = bot self.voice = None self.player = None self.playlist = deque(maxlen=3) discord.opus.load_opus(find_library("opus"))
def _findlib(libnames, path=None): """.""" platform = sys.platform if platform in ("win32", "cli"): pattern = "%s.dll" elif platform == "darwin": pattern = "lib%s.dylib" else: pattern = "lib%s.so" searchfor = libnames if type(libnames) is dict: # different library names for the platforms if platform == "cli" and platform not in libnames: # if not explicitly specified, use the Win32 libs for IronPython platform = "win32" if platform not in libnames: platform = "DEFAULT" searchfor = libnames[platform] results = [] if path: for libname in searchfor: for subpath in str.split(path, os.pathsep): dllfile = os.path.join(subpath, pattern % libname) if os.path.exists(dllfile): results.append(dllfile) for libname in searchfor: dllfile = find_library(libname) if dllfile: results.append(dllfile) return results