我们从Python开源项目中,提取了以下46个代码示例,用于说明如何使用ctypes.cdll.LoadLibrary()。
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 check_so(soname): """ Verify that we do have the 'soname' lib present in the system, and that it can be loaded. """ if len(get_available_gpus()) == 0: return None # Try to force load lib, this would fail if the lib is not there :) try: lib = cdll.LoadLibrary(soname) print("INFO: Found so as", lib) assert lib.__class__.__name__ == 'CDLL' assert lib._name == soname return True except OSError as ex: print("WARNING:", ex) return False
def _errno_location(): """ Try to get errno integer from libc using __errno_location_sym function. This function is specific to OS with "libc.so.6" and may fails for thread-safe libc. """ from ctypes import cdll try: libc = cdll.LoadLibrary("libc.so.6") except OSError: # Unable to open libc dynamic library return None try: __errno_location = libc.__errno_location_sym except AttributeError: # libc doesn't have __errno_location return None __errno_location.restype = POINTER(c_int) return __errno_location()[0]
def _load_lib(self, lib_path): """ Loads the libdivert library, and configuring its arguments type :param lib_path: The OS path where to load the libdivert.so :return: None """ self._lib = cdll.LoadLibrary(lib_path) # set the types of parameters for func_name, argtypes in self.divert_argtypes.items(): # first check if function exists if not hasattr(self._lib, func_name): raise RuntimeError("Not a valid libdivert library") setattr(getattr(self._lib, func_name), "argtypes", argtypes) # set the types of return value for func_name, restype in self.divert_restypes.items(): setattr(getattr(self._lib, func_name), "restype", restype)
def set_proc_name(newname): '''Set the process name seen by the OS in ps, for example ''' log("Entering {0}.".format(sys._getframe().f_code.co_name), level='DEBUG') # This works on EOS but not on OSX. Wrapped in try for testability. try: libc = cdll.LoadLibrary('libc.so.6') buff = create_string_buffer(len(newname) + 1) buff.value = newname libc.prctl(15, byref(buff), 0, 0, 0) except: log("Unable to set process name", level='DEBUG') if DEBUG: print "proc_name: {0}\n".format(sys.argv[0])
def __init__(self, original_name, shared_library_name='libstrategies.so'): """ Parameters ---------- original_name: str The name of the fortran function from the original axelrod tournament game: axelrod.Game A instance of an axelrod Game """ super().__init__() self.shared_library_name = shared_library_name self.shared_library = cdll.LoadLibrary(shared_library_name) self.original_name = original_name self.original_function = self.original_name is_stochastic = characteristics[self.original_name]['stochastic'] if is_stochastic is not None: self.classifier['stochastic'] = is_stochastic
def connect(s): s.so = cdll.LoadLibrary(s.so_path) if s.debug: s.tbk_ndx = Int() s.tbk_dotted = Char(size=fytbk.dotted_size, shape=[fytbk.max_depth]) s.tbk_lineno = Int(shape=[fytbk.max_depth]) s.tbk_last_error = Char(size=fytbk.last_error_size) s.tbk_verbose = Int() s.tbk_ndx.in_so(s.so, s.tbk_ndx_name) s.tbk_dotted.in_so(s.so, s.tbk_dotted_name) s.tbk_lineno.in_so(s.so, s.tbk_lineno_name) s.tbk_last_error.in_so(s.so, s.tbk_last_error_name) s.tbk_verbose.in_so(s.so, s.tbk_verbose_name) if s.has_main and s.run_main: s.main()
def __init__(self, path="./libsimilarity/libsimilarity.so"): super(SIMILARITYNative, self).__init__(True) self._u = cdll.LoadLibrary( path ) self._u.compress.restype = c_uint self._u.ncd.restype = c_int self._u.ncs.restype = c_int self._u.cmid.restype = c_int self._u.entropy.restype = c_double self._u.levenshtein.restype = c_uint self._u.kolmogorov.restype = c_uint self._u.bennett.restype = c_double self._u.RDTSC.restype = c_double self.__libsim_t = LIBSIMILARITY_T() self.set_compress_type( ZLIB_COMPRESS )
def test(): from ctypes import cdll if os.name == "nt": print cdll.msvcrt print cdll.load("msvcrt") print find_library("msvcrt") if os.name == "posix": # find and load_version print find_library("m") print find_library("c") print find_library("bz2") # getattr ## print cdll.m ## print cdll.bz2 # load if sys.platform == "darwin": print cdll.LoadLibrary("libm.dylib") print cdll.LoadLibrary("libcrypto.dylib") print cdll.LoadLibrary("libSystem.dylib") print cdll.LoadLibrary("System.framework/System") else: print cdll.LoadLibrary("libm.so") print cdll.LoadLibrary("libcrypt.so") print find_library("crypt")
def get_func(libname, funcname, restype=None, argtypes=()): """Retrieve a function from a library, and set the data types.""" from ctypes import cdll lib = cdll.LoadLibrary(libname) func = getattr(lib, funcname) func.argtypes = argtypes func.restype = restype return func
def _load_lib(): dirname = os.path.dirname(os.path.abspath(__file__)) ext = 'dylib' if sys.platform.startswith('darwin') else 'so' fname = os.path.join(dirname, 'libhuman_name.' + ext) return cdll.LoadLibrary(fname)
def _win_bindtextdomain(self, localedomain, localedir): """ Help routine for loading and setting up libintl attributes Returns libintl """ from ctypes import cdll try: libintl = cdll.LoadLibrary('libintl-8') libintl.bindtextdomain(localedomain, localedir) libintl.textdomain(localedomain) libintl.bind_textdomain_codeset(localedomain, "UTF-8") except WindowsError: LOG.warning("Localization library libintl not on %PATH%, localization will be incomplete")
def noalsaerr(): asound = cdll.LoadLibrary('libasound.so') asound.snd_lib_error_set_handler(c_error_handler) yield asound.snd_lib_error_set_handler(None)
def loadAwaLibrary(self, path): # link libawa self._lib = cdll.LoadLibrary(path)
def setCPUAffinity(): """ :note: Child processes inherit the parent's affinity. """ cpus = multiprocessing.cpu_count() libc = cdll.LoadLibrary("libc.so.6") # Using zero as first parameter means "self PID" res = libc.sched_setaffinity(0, 4, byref(c_int(0x00000001 << (cpus - 1)))) # Give our process a chance to migrate to a different CPU if necessary time.sleep(0.25) return res
def set_process_name(name): from ctypes import cdll, byref, create_string_buffer # This is nice to have for debugging, not essential try: libc = cdll.LoadLibrary('libc.so.6') buf = create_string_buffer(bytes(name, 'utf-8')) libc.prctl(15, byref(buf), 0, 0, 0) except: pass # export common proxies variables from datastore to environment
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(): from ctypes import cdll if os.name == "nt": print(cdll.msvcrt) print(cdll.load("msvcrt")) print(find_library("msvcrt")) if os.name == "posix": # find and load_version print(find_library("m")) print(find_library("c")) print(find_library("bz2")) # getattr ## print cdll.m ## print cdll.bz2 # load if sys.platform == "darwin": print(cdll.LoadLibrary("libm.dylib")) print(cdll.LoadLibrary("libcrypto.dylib")) print(cdll.LoadLibrary("libSystem.dylib")) print(cdll.LoadLibrary("System.framework/System")) else: print(cdll.LoadLibrary("libm.so")) print(cdll.LoadLibrary("libcrypt.so")) print(find_library("crypt"))
def _load_libc(self): self._libc = cdll.LoadLibrary('libc.dylib') # set the types of parameters for func_name, argtypes in self.libc_argtypes.items(): if not hasattr(self._libc, func_name): raise RuntimeError("Not a valid libC library") setattr(getattr(self._libc, func_name), "argtypes", argtypes) # set the types of return value for func_name, restype in self.libc_restypes.items(): setattr(getattr(self._libc, func_name), "restype", restype)
def test(): from ctypes import cdll if os.name == "nt": sys.stdout.write('%s\n' % (cdll.msvcrt,)) sys.stdout.write('%s\n' % (cdll.load("msvcrt"),)) sys.stdout.write('%s\n' % (find_library("msvcrt"),)) if os.name == "posix": # find and load_version sys.stdout.write('%s\n' % (find_library("m"),)) sys.stdout.write('%s\n' % (find_library("c"),)) sys.stdout.write('%s\n' % (find_library("bz2"),)) # getattr ## print_ cdll.m ## print_ cdll.bz2 # load if sys.platform == "darwin": sys.stdout.write('%s\n' % (cdll.LoadLibrary("libm.dylib"),)) sys.stdout.write('%s\n' % (cdll.LoadLibrary("libcrypto.dylib"),)) sys.stdout.write('%s\n' % (cdll.LoadLibrary("libSystem.dylib"),)) sys.stdout.write('%s\n' % (cdll.LoadLibrary("System.framework/System"),)) else: sys.stdout.write('%s\n' % (cdll.LoadLibrary("libm.so"),)) sys.stdout.write('%s\n' % (cdll.LoadLibrary("libcrypt.so"),)) sys.stdout.write('%s\n' % (find_library("crypt"),))
def __init__(self, model_path, user_dict_path, t2s, just_seg, pre_alloc_size=1024*1024*16): root = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) #??so????? self._lib = cdll.LoadLibrary(root+'/libthulac.so') #??so?? self._lib.init(c_char_p(fixCCP(model_path)), c_char_p(fixCCP(user_dict_path)), int(pre_alloc_size), int(t2s), int(just_seg)) #?????????
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 __init__(self, debug=""): self.dll = cdll.LoadLibrary("libaravis-0.4.so") if debug: self.dll.arv_debug_enable(debug) self.g = cdll.LoadLibrary("libgobject-2.0.so") self.g.g_type_init(None) self.gt = cdll.LoadLibrary("libgthread-2.0.so") self.gt.g_thread_init(None) self.dll.arv_debug_enable(None)
def suppress_alsa_errors(): asound = cdll.LoadLibrary('libasound.so') asound.snd_lib_error_set_handler(C_ERROR_HANDLER) yield asound.snd_lib_error_set_handler(None)
def set_proc_name(newname): from ctypes import cdll, byref, create_string_buffer libc = cdll.LoadLibrary('libc.so.6') buff = create_string_buffer(len(newname)+1) buff.value = newname.encode("ascii") libc.prctl(15, byref(buff), 0, 0, 0)
def ssdeepMe(path): # Load ssdeep lib ssdeepdll = cdll.LoadLibrary(os.path.join(os.path.abspath(os.path.dirname(__file__)), 'fuzzy.dll')) if path is not None: result = create_string_buffer(FUZZY_MAX_RESULT) ssdeepdll.fuzzy_hash_filename(path, result) return result.value else: print("Ssdeep: provide a file path") return ""
def set_process_name(name: str) -> bool: """Set process name and cpu priority.""" name = str(name).lower().strip() try: libc = cdll.LoadLibrary("libc.so.6") # set process name buff = create_string_buffer(len(name) + 1) buff.value = bytes(name.encode("utf-8")) libc.prctl(15, byref(buff), 0, 0, 0) except Exception as error: log.warning(error) return False # this may fail on windows and its normal, so be silent. else: log.debug(f"Process with PID {os.getpid()} Name set to: {name}.") return True
def __init__(self): # make log dir for api log # logdir = os.path.join(sys.path[0], "log") # if not os.path.exists(logdir): # os.mkdir(logdir) dlldir = os.path.join( os.path.split(os.path.realpath(__file__))[0], "dll") if not os.path.exists(dlldir): print('??DLL????') return # change work directory cur_path = os.getcwd() os.chdir(dlldir) if isWindowsSystem(): self.h = CDLL("ctp_Quote.dll") else: self.h = cdll.LoadLibrary("./ctp_quote.so") self.h.CreateApi.argtypes = [] self.h.CreateApi.restype = c_void_p self.h.CreateSpi.argtypes = [] self.h.CreateSpi.restype = c_void_p self.api = None self.spi = None self.nRequestID = 0 self.h.Release.argtypes = [c_void_p] self.h.Release.restype = c_void_p self.h.Init.argtypes = [c_void_p] self.h.Init.restype = c_void_p self.h.Join.argtypes = [c_void_p] self.h.Join.restype = c_void_p self.h.GetTradingDay.argtypes = [c_void_p] self.h.GetTradingDay.restype = c_void_p self.h.RegisterFront.argtypes = [c_void_p, c_char_p] self.h.RegisterFront.restype = c_void_p self.h.RegisterNameServer.argtypes = [c_void_p, c_char_p] self.h.RegisterNameServer.restype = c_void_p self.h.RegisterFensUserInfo.argtypes = [c_void_p, c_void_p] self.h.RegisterFensUserInfo.restype = c_void_p self.h.RegisterSpi.argtypes = [c_void_p, c_void_p] self.h.RegisterSpi.restype = c_void_p self.h.ReqUserLogin.argtypes = [c_void_p, c_void_p, c_int32] self.h.ReqUserLogin.restype = c_void_p self.h.ReqUserLogout.argtypes = [c_void_p, c_void_p, c_int32] self.h.ReqUserLogout.restype = c_void_p # restore work directory os.chdir(cur_path)
def _CFSetup(): sc = cdll.LoadLibrary(find_library("SystemConfiguration")) cf = cdll.LoadLibrary(find_library("CoreFoundation")) sctable = [ ('SCDynamicStoreCopyProxies', [c_void_p], c_void_p), ] cftable = [ ('CFArrayGetCount', [c_void_p], c_int64), ('CFArrayGetValueAtIndex', [c_void_p, c_int64], c_void_p), ('CFDictionaryGetValue', [c_void_p, c_void_p], c_void_p), ('CFStringCreateWithCString', [c_void_p, c_char_p, c_int32], c_void_p), ('CFStringGetLength', [c_void_p], c_int32), ('CFStringGetCString', [c_void_p, c_char_p, c_int32, c_int32], c_int32), ('CFNumberGetValue', [c_void_p, c_int, c_void_p], c_int32), ('CFRelease', [c_void_p], None), ] scconst = [ 'kSCPropNetProxiesExceptionsList', 'kSCPropNetProxiesExcludeSimpleHostnames', 'kSCPropNetProxiesHTTPEnable', 'kSCPropNetProxiesHTTPProxy', 'kSCPropNetProxiesHTTPPort', 'kSCPropNetProxiesHTTPSEnable', 'kSCPropNetProxiesHTTPSProxy', 'kSCPropNetProxiesHTTPSPort', 'kSCPropNetProxiesFTPEnable', 'kSCPropNetProxiesFTPProxy', 'kSCPropNetProxiesFTPPort', 'kSCPropNetProxiesGopherEnable', 'kSCPropNetProxiesGopherProxy', 'kSCPropNetProxiesGopherPort', ] class CFProxy(object): def __init__(self): for mod, table in [(sc, sctable), (cf, cftable)]: for fname, argtypes, restype in table: func = getattr(mod, fname) func.argtypes = argtypes func.restype = restype setattr(self, fname, func) for k in scconst: v = None try: v = c_void_p.in_dll(sc, k) except ValueError: v = None setattr(self, k, v) return CFProxy()