Python源码示例:ctypes.CDLL
示例1
def _setup_cuda_object():
global _CUDA_OBJECT
global _HAS_CUDA
libnames = ('libcuda.so', 'libcuda.dylib', 'nvcuda.dll')
for libname in libnames:
try:
cuda = ctypes.CDLL(libname)
if cuda.cuInit(0) == _CUDA_SUCCESS:
_CUDA_OBJECT = cuda
_HAS_CUDA = True
else:
_CUDA_OBJECT = None
_HAS_CUDA = False
except OSError:
continue
else:
break
else:
_CUDA_OBJECT = None
_HAS_CUDA = False
示例2
def load_library(libname):
# numpy 1.6 has bug in ctypeslib.load_library, see numpy/distutils/misc_util.py
if '1.6' in numpy.__version__:
if (sys.platform.startswith('linux') or
sys.platform.startswith('gnukfreebsd')):
so_ext = '.so'
elif sys.platform.startswith('darwin'):
so_ext = '.dylib'
elif sys.platform.startswith('win'):
so_ext = '.dll'
else:
raise OSError('Unknown platform')
libname_so = libname + so_ext
return ctypes.CDLL(os.path.join(os.path.dirname(__file__), libname_so))
else:
_loaderpath = os.path.dirname(__file__)
return numpy.ctypeslib.load_library(libname, _loaderpath)
#Fixme, the standard resouce module gives wrong number when objects are released
#see http://fa.bianp.net/blog/2013/different-ways-to-get-memory-consumption-or-lessons-learned-from-memory_profiler/#fn:1
#or use slow functions as memory_profiler._get_memory did
示例3
def __init__(self):
dir_path = os.path.dirname(os.path.realpath(__file__))
self.lib = ctypes.CDLL('%s/build/dll/libmol.so' % dir_path)
# self.lib.Smiles2Graph.restype = ctypes.c_void_p
self.lib.PrepareBatchFeature.restype = ctypes.c_int
self.lib.DumpFeatures.restype = ctypes.c_int
self.lib.LoadMolGraph.restype = ctypes.c_int
self.lib.NodeFeatDim.restype = ctypes.c_int
self.lib.EdgeFeatDim.restype = ctypes.c_int
self.lib.NumNodes.restype = ctypes.c_int
self.lib.NumEdges.restype = ctypes.c_int
self.lib.EdgeList.restype = ctypes.c_void_p
self.num_node_feats = self.lib.NodeFeatDim()
self.num_edge_feats = self.lib.EdgeFeatDim()
示例4
def __init__(self, args):
dir_path = os.path.dirname(os.path.realpath(__file__))
self.lib = ctypes.CDLL('%s/build/dll/libs2v.so' % dir_path)
self.lib.GetGraphStruct.restype = ctypes.c_void_p
self.lib.PrepareBatchGraph.restype = ctypes.c_int
self.lib.PrepareMeanField.restype = ctypes.c_int
self.lib.PrepareLoopyBP.restype = ctypes.c_int
self.lib.NumEdgePairs.restype = ctypes.c_int
if sys.version_info[0] > 2:
args = [arg.encode() for arg in args] # str -> bytes for each element in args
arr = (ctypes.c_char_p * len(args))()
arr[:] = args
self.lib.Init(len(args), arr)
self.batch_graph_handle = ctypes.c_void_p(self.lib.GetGraphStruct())
示例5
def __init__(self, ticket_number_key, request_data_key,
libcrypto_path=None):
self.check_des_key(ticket_number_key)
self.check_des_key(request_data_key)
self.ticket_number_key = ticket_number_key
self.request_data_key = request_data_key
if not libcrypto_path:
from ctypes.util import find_library
libcrypto_path = find_library('crypto')
if not libcrypto_path:
raise Exception('libcrypto(OpenSSL) not found')
self.libcrypto = ctypes.CDLL(libcrypto_path)
if hasattr(self.libcrypto, 'OpenSSL_add_all_ciphers'):
self.libcrypto.OpenSSL_add_all_ciphers()
示例6
def mkl_get_nthreads():
"""wrapper around MKL ``get_max_threads``.
Returns
-------
max_threads : int
The maximum number of threads used by MKL. ``-1`` if unable to read out.
"""
try:
import mkl # available in conda MKL
return mkl.get_max_threads()
except ImportError:
try:
mkl_rt = ctypes.CDLL('libmkl_rt.so')
return mkl_rt.mkl_get_max_threads()
except OSError:
warnings.warn("MKL library not found: can't get nthreads")
return -1
示例7
def mkl_set_nthreads(n):
"""wrapper around MKL ``set_num_threads``.
Parameters
----------
n : int
the number of threads to use
Returns
-------
success : bool
whether the shared library was found and set.
"""
try:
import mkl # available in conda MKL
mkl.set_num_threads(n)
return True
except ImportError:
try:
mkl_rt = ctypes.CDLL('libmkl_rt.so')
mkl_rt.mkl_set_num_threads(ctypes.byref(ctypes.c_int(n)))
return True
except OSError:
warnings.warn("MKL library not found: can't set nthreads")
return False
示例8
def _load_lapack(libs=[
"libLAPACK.dylib", "libmkl_rt.so", "libmkl_intel_lp64.so", "liblapack.so",
"libopenblas.dll",
find_library('lapack')
],
warn=True):
"""load & return a CLAPACK library."""
global _lapack_lib
if _lapack_lib is None:
for l in libs:
if l is None:
continue
try:
_lapack_lib = CDLL(l)
_set_CLAPACK_callsignatures(_lapack_lib)
if warn:
warnings.warn("[Loaded " + l + " for gesvd]")
break
except OSError:
pass
if _lapack_lib is None:
msg = "Couldn't find LAPACK library for 'gesvd' workaround.\nTried: " + str(libs)
raise EnvironmentError(msg)
warnings.warn("Old Scipy version. We will drop the support!", FutureWarning)
return _lapack_lib
示例9
def monotonicInit(self):
try:
from RMOSGlue.rmOSPlatform import RMOSPlatform
if RMOSPlatform().AUTODETECTED == RMOSPlatform.ANDROID:
librt = ctypes.CDLL('libc.so', use_errno=True)
log.info("Initialised Android monotonic clock")
elif RMOSPlatform().AUTODETECTED == RMOSPlatform.OPENWRT:
librt = ctypes.CDLL('librt.so.0', use_errno=True)
log.info("Initialised OpenWRT monotonic clock")
else:
librt = ctypes.CDLL('librt.so.1', use_errno=True)
log.info("Initialised generic monotonic clock")
self.clock_gettime = librt.clock_gettime
self.clock_gettime.argtypes = [ctypes.c_int, ctypes.POINTER(timespec)]
self.get = self.monotonicTime
except Exception, e:
self.get = self.monotonicFallback
log.error("Cannot initialise monotonicClock will use fallback time.time() method !")
示例10
def _set_proc_title(process_name: str) -> None:
"""
BSD specific calls (should be compataible with both FreeBSD and OpenBSD:
http://fxr.watson.org/fxr/source/gen/setproctitle.c?v=FREEBSD-LIBC
http://www.rootr.net/man/man/setproctitle/3
"""
libc = ctypes.CDLL(ctypes.util.find_library('c'))
name_buffer = ctypes.create_string_buffer(len(process_name) + 1)
name_buffer.value = process_name.encode()
try:
libc.setproctitle(ctypes.byref(name_buffer))
except AttributeError:
# Possible issue (seen on OSX):
# AttributeError: dlsym(0x7fff6a41d1e0, setproctitle): symbol not found
pass
示例11
def get_os_tid():
"""
Get the Linux process id associated with the current thread
Returns:
int: The process id
"""
if sys.platform.startswith(u'linux'):
return ctypes.CDLL(u'libc.so.6').syscall(186)
else:
# TODO: This is hacky - we need to replace it with something that actually returns the OS thread ID
if is_python_2():
return threading._get_ident()
else:
return threading.get_ident()
示例12
def _setup_environment(environ):
# Cygwin requires some special voodoo to set the environment variables
# properly so that Oracle will see them.
if platform.system().upper().startswith('CYGWIN'):
try:
import ctypes
except ImportError as e:
from django.core.exceptions import ImproperlyConfigured
raise ImproperlyConfigured("Error loading ctypes: %s; "
"the Oracle backend requires ctypes to "
"operate correctly under Cygwin." % e)
kernel32 = ctypes.CDLL('kernel32')
for name, value in environ:
kernel32.SetEnvironmentVariableA(name, value)
else:
os.environ.update(environ)
示例13
def __init__(self, args):
dir_path = os.path.dirname(os.path.realpath(__file__))
self.lib = ctypes.CDLL('%s/build/dll/libgnn.so' % dir_path)
self.lib.GetGraphStruct.restype = ctypes.c_void_p
self.lib.PrepareBatchGraph.restype = ctypes.c_int
self.lib.PrepareSparseMatrices.restype = ctypes.c_int
self.lib.NumEdgePairs.restype = ctypes.c_int
if sys.version_info[0] > 2:
args = [arg.encode() for arg in args] # str -> bytes for each element in args
arr = (ctypes.c_char_p * len(args))()
arr[:] = args
self.lib.Init(len(args), arr)
self.batch_graph_handle = ctypes.c_void_p(self.lib.GetGraphStruct())
示例14
def have_compatible_glibc(major, minimum_minor):
# ctypes.CDLL(None) internally calls dlopen(NULL), and as the dlopen
# manpage says, "If filename is NULL, then the returned handle is for the
# main program". This way we can let the linker do the work to figure out
# which libc our process is actually using.
process_namespace = ctypes.CDLL(None)
try:
gnu_get_libc_version = process_namespace.gnu_get_libc_version
except AttributeError:
# Symbol doesn't exist -> therefore, we are not linked to
# glibc.
return False
# Call gnu_get_libc_version, which returns a string like "2.5".
gnu_get_libc_version.restype = ctypes.c_char_p
version_str = gnu_get_libc_version()
# py2 / py3 compatibility:
if not isinstance(version_str, str):
version_str = version_str.decode("ascii")
return check_glibc_version(version_str, major, minimum_minor)
示例15
def copyload_shared_lib(dst_prefix=TESTFILE_PREFIX):
"""Ctx manager which picks up a random shared CO lib used
by this process, copies it in another location and loads it
in memory via ctypes. Return the new absolutized path.
"""
ext = ".so"
dst = tempfile.mktemp(prefix=dst_prefix, suffix=ext)
libs = [x.path for x in psutil.Process().memory_maps() if
os.path.splitext(x.path)[1] == ext and
'python' in x.path.lower()]
src = random.choice(libs)
shutil.copyfile(src, dst)
try:
ctypes.CDLL(dst)
yield dst
finally:
safe_rmpath(dst)
示例16
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
#FIXME mach_port_insert_right
self.portset = self.newMachPort(MACH_PORT_RIGHT_PORT_SET)
self.excport = self.newMachRWPort()
self.addPortToSet(self.excport)
示例17
def copyload_shared_lib(suffix=""):
"""Ctx manager which picks up a random shared CO lib used
by this process, copies it in another location and loads it
in memory via ctypes. Return the new absolutized path.
"""
exe = 'pypy' if PYPY else 'python'
ext = ".so"
dst = get_testfn(suffix=suffix + ext)
libs = [x.path for x in psutil.Process().memory_maps() if
os.path.splitext(x.path)[1] == ext and
exe in x.path.lower()]
src = random.choice(libs)
shutil.copyfile(src, dst)
try:
ctypes.CDLL(dst)
yield dst
finally:
safe_rmpath(dst)
示例18
def load_ctypes_library(name, signatures, error_checkers):
"""
Load library ``name`` and return a :class:`ctypes.CDLL` object for it.
:param str name: the library name
:param signatures: signatures of methods
:type signatures: dict of str * (tuple of (list of type) * type)
:param error_checkers: error checkers for methods
:type error_checkers: dict of str * ((int * ptr * arglist) -> int)
The library has errno handling enabled.
Important functions are given proper signatures and return types to support
type checking and argument conversion.
:returns: a loaded library
:rtype: ctypes.CDLL
:raises ImportError: if the library is not found
"""
library_name = find_library(name)
if not library_name:
raise ImportError('No library named %s' % name)
lib = CDLL(library_name, use_errno=True)
# Add function signatures
for funcname, signature in signatures.items():
function = getattr(lib, funcname, None)
if function:
argtypes, restype = signature
function.argtypes = argtypes
function.restype = restype
errorchecker = error_checkers.get(funcname)
if errorchecker:
function.errcheck = errorchecker
return lib
示例19
def _load_lib():
"""Load library by searching possible path."""
lib_path = libinfo.find_lib_path()
lib = ctypes.CDLL(lib_path[0], ctypes.RTLD_LOCAL)
# DMatrix functions
lib.MXGetLastError.restype = ctypes.c_char_p
return lib
# version number
示例20
def init():
"""
Initializes the ntfsea library.
"""
if ntfsea.lib is None:
if hasattr(ctypes, 'WinDLL'):
loader = ctypes.WinDLL
else:
loader = ctypes.CDLL
ntfsea.lib = loader('ntfsea_%s.dll' % ('x64' if platform.architecture()[0] == '64bit' else 'x86'))
ntfsea.lib.GetEaList.restype = ctypes.POINTER(ntfsea_EaList)
ntfsea.lib.GetEa.restype = ctypes.POINTER(ntfsea_Ea)
ntfsea.lib.WriteEa.restype = ctypes.c_int
示例21
def find_symbol(symname, lnames, paths):
for lname in lnames:
lib = find_lib(lname, paths)
if lib == None:
continue
try:
llib = ctypes.CDLL(lib, use_errno = True)
return llib.__getitem__(symname)
except:
continue
raise Exception('Bah, %s cannot be found in libs %s in the paths %s' % (symname, lnames, paths))
示例22
def _pep425_supports_manylinux():
"""
:return:
A boolean indicating if the machine can use manylinux1 packages
"""
try:
import _manylinux
return bool(_manylinux.manylinux1_compatible)
except (ImportError, AttributeError):
pass
# Check for glibc 2.5
try:
proc = ctypes.CDLL(None)
gnu_get_libc_version = proc.gnu_get_libc_version
gnu_get_libc_version.restype = ctypes.c_char_p
ver = gnu_get_libc_version()
if not isinstance(ver, str_cls):
ver = ver.decode('ascii')
match = re.match(r'(\d+)\.(\d+)', ver)
return match and match.group(1) == '2' and int(match.group(2)) >= 5
except (AttributeError):
return False
示例23
def main():
# Load the shared object file containing the Clip plugin implementation.
# By doing this, you will also register the Clip plugin with the TensorRT
# PluginRegistry through use of the macro REGISTER_TENSORRT_PLUGIN present
# in the plugin implementation. Refer to plugin/clipPlugin.cpp for more details.
if not os.path.isfile(CLIP_PLUGIN_LIBRARY):
raise IOError("\n{}\n{}\n{}\n".format(
"Failed to load library ({}).".format(CLIP_PLUGIN_LIBRARY),
"Please build the Clip sample plugin.",
"For more information, see the included README.md"
))
ctypes.CDLL(CLIP_PLUGIN_LIBRARY)
# Load pretrained model
if not os.path.isfile(MODEL_PATH):
raise IOError("\n{}\n{}\n{}\n".format(
"Failed to load model file ({}).".format(MODEL_PATH),
"Please use 'python lenet5.py' to train and save the model.",
"For more information, see the included README.md"
))
# Build an engine and retrieve the image mean from the model.
with build_engine(MODEL_PATH) as engine:
inputs, outputs, bindings, stream = common.allocate_buffers(engine)
with engine.create_execution_context() as context:
print("\n=== Testing ===")
test_case = load_normalized_test_case(inputs[0].host)
print("Loading Test Case: " + str(test_case))
# The common do_inference function will return a list of outputs - we only have one in this case.
[pred] = common.do_inference(context, bindings=bindings, inputs=inputs, outputs=outputs, stream=stream)
print("Prediction: " + str(np.argmax(pred)))
示例24
def main():
# Load the shared object file containing the Clip plugin implementation.
# By doing this, you will also register the Clip plugin with the TensorRT
# PluginRegistry through use of the macro REGISTER_TENSORRT_PLUGIN present
# in the plugin implementation. Refer to plugin/clipPlugin.cpp for more details.
if not os.path.isfile(CLIP_PLUGIN_LIBRARY):
raise IOError("\n{}\n{}\n{}\n".format(
"Failed to load library ({}).".format(CLIP_PLUGIN_LIBRARY),
"Please build the Clip sample plugin.",
"For more information, see the included README.md"
))
ctypes.CDLL(CLIP_PLUGIN_LIBRARY)
# Load pretrained model
if not os.path.isfile(MODEL_PATH):
raise IOError("\n{}\n{}\n{}\n".format(
"Failed to load model file ({}).".format(MODEL_PATH),
"Please use 'python lenet5.py' to train and save the model.",
"For more information, see the included README.md"
))
# Build an engine and retrieve the image mean from the model.
with build_engine(MODEL_PATH) as engine:
inputs, outputs, bindings, stream = common.allocate_buffers(engine)
with engine.create_execution_context() as context:
print("\n=== Testing ===")
test_case = load_normalized_test_case(inputs[0].host)
print("Loading Test Case: " + str(test_case))
# The common do_inference function will return a list of outputs - we only have one in this case.
[pred] = common.do_inference(context, bindings=bindings, inputs=inputs, outputs=outputs, stream=stream)
print("Prediction: " + str(np.argmax(pred)))
示例25
def get_libmkl():
if sys.platform == 'darwin':
return ctypes.CDLL('libmkl_rt.dylib')
elif sys.platform == 'win32':
return ctypes.CDLL('mkl_rt.dll')
else:
return ctypes.CDLL('libmkl_rt.so')
示例26
def _load_plugins(self):
ctypes.CDLL("models/ssd_mobilenet/libflattenconcat.so")
trt.init_libnvinfer_plugins(self.trt_logger, '')
示例27
def libgl_workaround() -> None:
"""Work around QOpenGLShaderProgram issues, especially for Nvidia.
See https://bugs.launchpad.net/ubuntu/+source/python-qt4/+bug/941826
"""
if os.environ.get('QUTE_SKIP_LIBGL_WORKAROUND'):
return
libgl = ctypes.util.find_library("GL")
if libgl is not None: # pragma: no branch
ctypes.CDLL(libgl, mode=ctypes.RTLD_GLOBAL)
示例28
def check_libsqlite(cls):
# Checking compile options is not supported.
if sys.platform.startswith('win'):
library = 'libsqlite3.dll'
elif sys.platform == 'darwin':
library = 'libsqlite3.dylib'
else:
library = 'libsqlite3.so'
try:
libsqlite = ctypes.CDLL(library)
except OSError:
return False
return libsqlite.sqlite3_compileoption_used('BERKELEY_DB') == 1
示例29
def test_NPY_NO_EXPORT():
cdll = ctypes.CDLL(np.core._multiarray_tests.__file__)
# Make sure an arbitrary NPY_NO_EXPORT function is actually hidden
f = getattr(cdll, 'test_not_exported', None)
assert f is None, ("'test_not_exported' is mistakenly exported, "
"NPY_NO_EXPORT does not work")
示例30
def glibc_version_string():
"Returns glibc version string, or None if not using glibc."
# ctypes.CDLL(None) internally calls dlopen(NULL), and as the dlopen
# manpage says, "If filename is NULL, then the returned handle is for the
# main program". This way we can let the linker do the work to figure out
# which libc our process is actually using.
process_namespace = ctypes.CDLL(None)
try:
gnu_get_libc_version = process_namespace.gnu_get_libc_version
except AttributeError:
# Symbol doesn't exist -> therefore, we are not linked to
# glibc.
return None
# Call gnu_get_libc_version, which returns a string like "2.5"
gnu_get_libc_version.restype = ctypes.c_char_p
version_str = gnu_get_libc_version()
# py2 / py3 compatibility:
if not isinstance(version_str, str):
version_str = version_str.decode("ascii")
return version_str
# Separated out from have_compatible_glibc for easier unit testing