def convert_library(self, lib): library_cache = self.library_cache if isinstance(lib, str): if lib not in library_cache: library_cache[lib] = _ctypes.CDLL(_find_library(lib)) return library_cache[lib] else: return lib
def find_library(lib_name, paths=None, exts=None): """ Search for library in all permutations of `paths` and `exts`. If nothing is found None is returned. """ if not paths or not exts: lib = _find_library(lib_name) if lib is None and lib_name.startswith('lib'): lib = _find_library(lib_name[3:]) return lib for lib_name in [lib_name] + ([lib_name[3:]] if lib_name.startswith('lib') else []): for path in paths: for ext in exts: lib_path = os.path.join(path, lib_name + ext) if os.path.exists(lib_path): return lib_path return None
def _load_library(name): if _sys.version_info[0]==2 and _sys.version_info[1]<5 and _os.name=='posix' and _sys.platform.startswith('linux'): return _C.CDLL('lib'+name+'.so') libnam=_find_library(name) if libnam is None: raise Exception("Error finding library: "+name) else: try: lib=_C.CDLL(libnam) except: try: lib=_C.CDLL(name) except: lib=_C.CDLL(_os.path.basename(libnam)) return lib
def _load_library(name): if os.name == 'nt': return _C.CDLL(name) elif os.name == "posix" and sys.platform == "darwin": lib=_find_library(name) if lib is None: raise Exception,"Error finding library: "+name else: return _C.CDLL(lib) else: try: return _C.CDLL('lib'+name+'.so') except: return _C.CDLL('lib'+name+'.sl') raise Exception,"Error finding library: "+name
def _init(): glfw_library = None # First if there is an environment variable pointing to the library if 'GLFW_LIBRARY' in _os.environ: library_path = _os.path.realpath(_os.environ['GLFW_LIBRARY']) if _os.path.exists(library_path): glfw_library = library_path # Else, try to find it if glfw_library is None: ordered_library_names = ['glfw', 'glfw3'] for library_name in ordered_library_names: glfw_library = _find_library(library_name) if glfw_library is not None: break # Else, we failed and exit if glfw_library is None: raise OSError('GLFW library not found') # Parse header api_path = _os.path.join(_os.path.dirname(__file__), 'glfw3-api.h') with open(api_path, 'r') as f: source = f.read() _ffi.cdef(source) global _glfw _glfw = _ffi.dlopen(glfw_library) if False: # Dump the functions function_re = re.compile('^.* glfw([A-Za-z]*)\(.*;$') camel_case_re = re.compile('(?!^)([A-Z]+)') for line in source.split('\n'): match = function_re.match(line) if match: camel_case_function = match.group(1) function = camel_case_re.sub(r'_\1', camel_case_function).lower() six.print_('{} = _glfw.glfw{}'.format(function, camel_case_function))
def find_library(name): """ Returns the shared library filename for a given library. The library name is given without any prefixes or suffixes--(e.g. just "Singular", not "libSingular", as shared library naming is platform-specific. This does ''not'' currently return the absolute path of the file on most platforms; see https://bugs.python.org/issue21042 EXAMPLES:: sage: from sage.misc.compat import find_library sage: find_library('Singular') '...Singular...' """ return _find_library(name)
def _init(): glfw_library = None # First if there is an environment variable pointing to the library if 'GLFW_LIBRARY' in _os.environ: library_path = _os.path.realpath(_os.environ['GLFW_LIBRARY']) if _os.path.exists(library_path): glfw_library = library_path # Else, try to find it if glfw_library is None: ordered_library_names = ['glfw', 'glfw3'] for library_name in ordered_library_names: glfw_library = _find_library(library_name) if glfw_library is not None: break # Else, we failed and exit if glfw_library is None: raise OSError('GLFW library not found') # Parse header api_path = _os.path.join(_os.path.dirname(__file__), 'glfw3-api.h') with open(api_path, 'r') as f: source = f.read() _ffi.cdef(source) global _glfw _glfw = _ffi.dlopen(glfw_library) if False: # Dump the functions function_re = re.compile('^.* glfw([A-Za-z]*)\(.*;$') camel_case_re = re.compile('(?!^)([A-Z]+)') for line in source.split('\n'): match = function_re.match(line) if match: camel_case_function = match.group(1) function = camel_case_re.sub( r'_\1', camel_case_function).lower() six.print_('{} = _glfw.glfw{}'.format(function, camel_case_function))
if 'MUPDF_LIBRARY_PATH' in os.environ: mupdf_library_path = os.path.realpath(os.environ['MUPDF_LIBRARY_PATH']) library_path = os.path.join(mupdf_library_path, 'libmupdf.a') # Fixme: Linux if os.path.exists(library_path): mupdf_library = library_path libraries = ['mupdf', 'mupdfthird'] elif 'MUPDF_SHARED_LIBRARY' in os.environ: library_path = os.path.realpath(os.environ['MUPDF_SHARED_LIBRARY']) if os.path.exists(library_path): mupdf_library = library_path # Else, try to find it # search for shared library if mupdf_library is None: library_name = 'mupdf' mupdf_library = _find_library(library_name) # search for static library if mupdf_library is None: for path in ( # Fixme: Linux '/usr/lib64/libmupdf.a', '/usr/local/lib/libmupdf.a', ): if os.path.exists(path): mupdf_library = path libraries = ['mupdf', 'mupdfthird'] # Fixme: depend how it was compiled ... # Else, we failed and exit if mupdf_library is None: raise OSError('MUPDF library not found')
except: # make dll searching a bit more like windows does it # save path old_path = os.environ["PATH"] # add the directory containing the main script to path, if any import __main__ if hasattr(__main__, "__file__") and __main__.__file__: os.environ["PATH"] = os.path.dirname(os.path.abspath(__main__.__file__)) + os.pathsep + os.environ["PATH"] del __main__ # add cwd to path os.environ["PATH"] = os.path.abspath(".") + os.pathsep + os.environ["PATH"] # try to find the library glfw_loc = _find_library("glfw") # restore old path os.environ["PATH"] = old_path del old_path if glfw_loc is None: raise RuntimeError("no GLFW shared library found") else: warnings.warn("no GLFW shared library found in the module directory, using the system's library", RuntimeWarning) _glfwdll = _ctypes.windll.LoadLibrary(glfw_loc) del glfw_loc else: try: _glfwdll = _ctypes.cdll.LoadLibrary(os.path.abspath(os.path.join(os.path.dirname(__file__), "libglfw.so")))
# the program, which happens when PyTorch loads OpenMP runtime first. Not that # this method is "unsafe, unsupported, undocumented", but we found it to be # generally safe to use. This should be deprecated once we found a way to # "ensure that only a single OpenMP runtime is linked into the process". # # https://github.com/llvm-mirror/openmp/blob/8453ca8594e1a5dd8a250c39bf8fcfbfb1760e60/runtime/src/i18n/en_US.txt#L449 # https://github.com/dmlc/xgboost/issues/1715 import os import sys os.environ['KMP_DUPLICATE_LIB_OK'] = 'True' from ctypes import CDLL as _CDLL from ctypes.util import find_library as _find_library from pathlib import Path as _Path from open3d._build_config import _build_config if _build_config["BUILD_GUI"] and not (_find_library('c++abi') or _find_library('c++')): try: # Preload libc++.so and libc++abi.so (required by filament) _CDLL(str(next((_Path(__file__).parent).glob('*c++abi.*')))) _CDLL(str(next((_Path(__file__).parent).glob('*c++.*')))) except StopIteration: # Not found: check system paths while loading pass __DEVICE_API__ = 'cpu' if _build_config["BUILD_CUDA_MODULE"]: # Load CPU pybind dll gracefully without introducing new python variable. # Do this before loading the CUDA pybind dll to correctly resolve symbols try: # StopIteration if cpu version not available _CDLL(str(next((_Path(__file__).parent / 'cpu').glob('pybind*')))) except StopIteration: pass
def _LoadLib(): libname = 'gmadShared' libpath = '/usr/local/lib/' parserlib = None test0, test1, test2, test3 = False, False, False, False #test0 - try general find function libpath0 = _find_library(libname) if libpath0 != None: parserlib = _ctypes.cdll.LoadLibrary(libpath0) test0 = True #test1 - pybdsim is being used from bdsim build dir _this_dir, _this_filename = _os.path.split(__file__) libpath1 = _this_dir + '/../../parser/' + 'lib' + libname if _os.path.exists(libpath1 + '.so'): parserlib = _ctypes.cdll.LoadLibrary(libpath1 + '.so') test1 = True elif _os.path.exists(libpath1 + ".dylib"): parserlib = _ctypes.cdll.LoadLibrary(libpath1 + '.so') test1 = True #test2 - try /usr/local/lib/libgmadShared.so try: fulllibname = 'lib' + libname + '.so' parserlib = _ctypes.cdll.LoadLibrary(libpath + fulllibname) test2 = True except OSError: pass #test3 - try /usr/local/lib/libgmadShared.dylib try: fulllibname = 'lib' + libname + '.dylib' parserlib = _ctypes.cdll.LoadLibrary(libpath + fulllibname) test3 = True except OSError: pass tests = [test0, test1, test2, test3] if tests.count(True) == 0: print('LoadLib - cannot find libgmadShared - check paths') raise OSError('LoadLib - cannot find libgmadShared - check paths') else: parserlib.GetNElements.restype = _ctypes.c_int parserlib.GetNElements.argstypes = [] parserlib.GetType.restype = _ctypes.c_int parserlib.GetType.argtypes = [_ctypes.c_int] parserlib.GetName.restype = _ctypes.c_char_p parserlib.GetName.argtypes = [_ctypes.c_int] parserlib.GetLength.restype = _ctypes.c_double parserlib.GetLength.argtypes = [_ctypes.c_int] parserlib.GetAngle.restype = _ctypes.c_double parserlib.GetAngle.argtypes = [_ctypes.c_int] parserlib.GetKs.restype = _ctypes.c_double * 10 parserlib.GetKs.argtypes = [_ctypes.c_int] parserlib.GetAper1.restype = _ctypes.c_double parserlib.GetAper1.argtypes = [_ctypes.c_int] parserlib.GetAper2.restype = _ctypes.c_double parserlib.GetAper2.argtypes = [_ctypes.c_int] parserlib.GetAper3.restype = _ctypes.c_double parserlib.GetAper3.argtypes = [_ctypes.c_int] parserlib.GetAper4.restype = _ctypes.c_double parserlib.GetAper4.argtypes = [_ctypes.c_int] parserlib.GetApertureType.restype = _ctypes.c_char_p parserlib.GetApertureType.argtypes = [_ctypes.c_int] parserlib.GetBeampipeThickness.restype = _ctypes.c_double parserlib.GetBeampipeThickness.argtypes = [_ctypes.c_int] return parserlib
"""Lowlevel wrappers around libsamplerate. The docstrings of the `src_*` functions are adapted from the libsamplerate header file. """ import os as _os import sys as _sys from ctypes.util import find_library as _find_library import numpy as _np # Locate and load libsamplerate from samplerate._src import ffi lib_basename = 'libsamplerate' lib_filename = _find_library('samplerate') if _os.environ.get('READTHEDOCS') == 'True': # Mock minimum C API for Read the Docs class MockLib(object): @classmethod def src_get_version(cls): return ffi.new('char[]', 'libsamplerate-0.1.9 (c) ...') lib_filename = 'mock' _lib = MockLib() elif lib_filename is None: if _sys.platform == 'darwin': lib_filename = '{}.dylib'.format(lib_basename) elif _sys.platform == 'win32': from platform import architecture
# --- Default to 3D if geometry is not setup yet. try: _prob_lo = geometry.prob_lo _coord_sys = geometry.coord_sys except AttributeError: geometry_dim = '3d' else: if _coord_sys == 0: geometry_dim = '%dd' % len(_prob_lo) elif _coord_sys == 1: geometry_dim = 'rz' else: raise Exception('Undefined coordinate system %d' % _coord_sys) del _prob_lo, _coord_sys _libc = ctypes.CDLL(_find_library('c')) try: libwarpx = ctypes.CDLL( os.path.join(_get_package_root(), "libwarpx%s.so" % geometry_dim)) except OSError: raise Exception( 'libwarpx%s.so was not installed. It can be installed by running "make" in the Python directory of WarpX' % geometry_dim) # WarpX can be compiled using either double or float libwarpx.warpx_Real_size.restype = ctypes.c_int libwarpx.warpx_ParticleReal_size.restype = ctypes.c_int _Real_size = libwarpx.warpx_Real_size() _ParticleReal_size = libwarpx.warpx_ParticleReal_size()
import ctypes import os import sys from ctypes import POINTER, byref from ctypes import c_char_p as char_p from ctypes import c_size_t as size_t from ctypes import c_void_p as void_p from ctypes import cast, create_string_buffer, sizeof from typing import List import numpy as np lib = None try: from ctypes.util import find_library as _find_library lib = ctypes.cdll.LoadLibrary(_find_library('OpenCL')) except: pass if lib is None: raise RuntimeError('Could not load OpenCL libary.') class cl_char(ctypes.c_int8): pass class cl_uchar(ctypes.c_uint8): pass class cl_short(ctypes.c_int16):
nondefaults = [] for opt in self.keys(): realind = moptions_et.fromname(opt).value if self.array[realind] != -1: val = self[opt] nondefaults.append('%s=%r' % (opt, val)) return 'METIS_Options(' + ', '.join(nondefaults) + ')' # Attempt to locate and load the appropriate shared library _dll_filename = os.getenv('METIS_DLL') if not _dll_filename: try: from ctypes.util import find_library as _find_library _dll_filename = _find_library('metis') except ImportError: pass if _dll_filename: try: _dll = ctypes.cdll.LoadLibrary(_dll_filename) except: raise RuntimeError('Could not load METIS dll: %s' % _dll_filename) else: if os.environ.get('READTHEDOCS', None) == 'True': # Don't care if we can load the DLL on RTD. _dll = None else: raise RuntimeError('Could not locate METIS dll. Please set the METIS_DLL environment variable to its full path.') # Wrapping conveniences
mupdf_library_path = os.path.realpath(os.environ['MUPDF_LIBRARY_PATH']) library_path = os.path.join(mupdf_library_path, 'libmupdf.a') # Fixme: Linux if os.path.exists(library_path): mupdf_library = library_path libraries = ['mupdf', 'mupdfthird'] elif 'MUPDF_SHARED_LIBRARY' in os.environ: library_path = os.path.realpath(os.environ['MUPDF_SHARED_LIBRARY']) if os.path.exists(library_path): mupdf_library = library_path # Else, try to find it # search for shared library if mupdf_library is None: library_name = 'mupdf' mupdf_library = _find_library(library_name) # search for static library if mupdf_library is None: for path in ( # Fixme: Linux '/usr/lib64/libmupdf.a', '/usr/local/lib/libmupdf.a', ): if os.path.exists(path): mupdf_library = path libraries = ['mupdf', 'mupdfthird'] # Fixme: depend how it was compiled ... # Else, we failed and exit if mupdf_library is None:
""" Only show non-default options """ nondefaults = [] for opt in self.keys(): realind = moptions_et.fromname(opt).value if self.array[realind] != -1: val = self[opt] nondefaults.append('%s=%r' % (opt, val)) return 'METIS_Options(' + ', '.join(nondefaults) + ')' # Attempt to locate and load the appropriate shared library _dll_filename = os.getenv('METIS_DLL') if not _dll_filename: try: from ctypes.util import find_library as _find_library _dll_filename = _find_library('metis') except ImportError: pass if _dll_filename == 'SKIP': warn( '$METIS_DLL=SKIP, skipping DLL load. Nothing will work. ' 'This is normal during install.', UserWarning, 2) _dll = None elif _dll_filename: try: _dll = ctypes.cdll.LoadLibrary(_dll_filename) except: raise RuntimeError('Could not load METIS dll: %s' % _dll_filename) else: if os.environ.get('READTHEDOCS', None) == 'True': # Don't care if we can load the DLL on RTD.
from ctypes.util import find_library as _find_library print(_find_library('sndfile')) print('test fine')