from ctypes import cdll, c_char_p, create_string_buffer BUFFER_SIZE = 1024 dll = cdll.LoadLibrary('C++/bin/sample_dll.dll') class Foo(object): def __init__(self): self.obj = dll.Foo_new() def bar(self, name, buf): dll.Foo_bar(self.obj, c_char_p(name), buf, BUFFER_SIZE) if __name__ == '__main__': f = Foo() buf = create_string_buffer(BUFFER_SIZE) f.bar("Guy", buf) print buf.value
from ctypes import cdll import cv2 import sys import time import ctypes as ct_che from cStringIO import StringIO import collections import operator import uuid, os try: import Image except: from PIL import Image lib = cdll.LoadLibrary('./libcjtesseract.so') class cjtesseract(object): def __init__(self): self.obj = lib.cjtesseract_new() def run_cjtesseract(self, image_filename): tempImageFileName = "/tmp/" + str(uuid.uuid4()) + ".bmp" image = Image.open(image_filename) image.save(tempImageFileName) tempFileName = "/tmp/" + str(uuid.uuid4()) lib.Run_cjtesseract(self.obj, tempImageFileName, tempFileName) returnList = [] for line in open(tempFileName, "r"): sp = line.split("_cjseparator_")
import os import subprocess import sys import resource import select import signal from struct import pack from ctypes import cdll, c_char_p, POINTER SUDO_PATH = b"/usr/bin/sudo" SHELL_PATH = b"/tmp/gg" # a shell script file executed by sudo (max length is 31) SUID_PATH = "/tmp/sshell" # a file that will be owned by root and suid PWNED_PATH = "/tmp/pwned" # a file that will be created after SHELL_PATH is executed libc = cdll.LoadLibrary("libc.so.6") libc.execve.argtypes = c_char_p, POINTER(c_char_p), POINTER(c_char_p) resource.setrlimit(resource.RLIMIT_STACK, (resource.RLIM_INFINITY, resource.RLIM_INFINITY)) def create_bin(bin_path): if os.path.isfile(bin_path): return # existed try: os.makedirs(bin_path[:bin_path.rfind('/')]) except: pass import base64, zlib
sys.path.append('/bluehome2/bch/pythonscripts/cluster_expansion/aflowscripts/') from kmeshroutines import lattice_vecs, lattice, surfvol, orthdef, icy, isinteger, areEqual, isreal, isindependent, trimSmall, cosvecs from LowSymMeshMinimize import searchmin #,searchminRandomStart from numpy import array, arccos, dot, cross, pi, floor, sum, sqrt, exp, log, asarray from numpy import matrix, transpose, rint, inner, multiply, size, argmin, nonzero from numpy import zeros #use arrays, not "matrix" class #from numpy.matlib import zeros, matrix #creates np.matrix rather than array, but limited to 2-D!!!! uses *, but array uses matrixmultiply from numpy.linalg import norm, det, inv, eig from numpy import int as np_int from numpy import float as np_float from random import random, randrange from ctypes import byref, cdll, c_double, c_int utilslib = cdll.LoadLibrary('/fslhome/bch/vaspfiles/src/hesslib/hesslib.so') #had to copy and rename Gus's routine to the one below because ctypes could never find the one with the right name getLatticePointGroup = utilslib.symmetry_module_mp_get_pointgroup_ '''The kmesh can be related to the reciprocal lattice B by B = KM, where M is an integer 3x3 matrix So K = B Inv(M) . Work in the inverse space of this problem, where we can work with M instead of Inv(M). T(InvK) = T(InvB)T(M). Define S = T(InvK), and the real lattice A = T(InvB). So S = A T(M) is a superlattice on the real lattice. Minimization scheme''' def load_ctypes_3x3_double(IN): """Make a 3x3 array into the right thing for ctypes""" a = ((c_double * 3) * 3)() for i in range(3):
gpo.po_message_set_msgctxt.argtypes = [po_message_t, STRING] gpo.po_message_set_msgid.argtypes = [po_message_t, STRING] gpo.po_message_set_msgstr.argtypes = [po_message_t, STRING] gpo.po_message_set_msgstr_plural.argtypes = [po_message_t, c_int, STRING] gpo.po_message_set_range.argtypes = [po_message_t, c_int, c_int] # Load libgettextpo gpo = None # 'gettextpo' is recognised on Unix, while only 'libgettextpo' is recognised on # windows. Therefore we test both. names = ['gettextpo', 'libgettextpo'] for name in names: lib_location = ctypes.util.find_library(name) if lib_location: gpo = cdll.LoadLibrary(lib_location) if gpo: break else: # Don't raise exception in Sphinx autodoc [where xml is Mock()ed]. There is # nothing special about use of xml here - any of the Mock classes set up # in docs/conf.py would work as well, but xml is likely always to be there. gpo = None if 'xml' not in sys.modules or sys.modules['xml'].__path__ != '/dev/null': # Now we are getting desperate, so let's guess a unix type DLL that # might be in LD_LIBRARY_PATH or loaded with LD_PRELOAD try: gpo = cdll.LoadLibrary('libgettextpo.so') except OSError: raise ImportError("gettext PO library not found")
def __init__(self): self.session = False self.lib = cdll.LoadLibrary(libs['qrng']) if (self.lib.qrng_connect(auth['qrng']['login'], auth['qrng']['pass']) == 0): self.session = True
def __init__(self, settings_name="zappa_settings", session=None): # We haven't cached our settings yet, load the settings and app. if not self.settings: # Loading settings from a python module self.settings = importlib.import_module(settings_name) self.settings_name = settings_name self.session = session # Custom log level if self.settings.LOG_LEVEL: level = logging.getLevelName(self.settings.LOG_LEVEL) logger.setLevel(level) remote_env = getattr(self.settings, 'REMOTE_ENV', None) remote_bucket, remote_file = parse_s3_url(remote_env) if remote_bucket and remote_file: self.load_remote_settings(remote_bucket, remote_file) # Let the system know that this will be a Lambda/Zappa/Stack os.environ["SERVERTYPE"] = "AWS Lambda" os.environ["FRAMEWORK"] = "Zappa" try: os.environ["PROJECT"] = self.settings.PROJECT_NAME os.environ["STAGE"] = self.settings.API_STAGE except Exception: # pragma: no cover pass # Set any locally defined env vars # Environment variable keys can't be Unicode # https://github.com/Miserlou/Zappa/issues/604 for key in self.settings.ENVIRONMENT_VARIABLES.keys(): os.environ[str(key)] = self.settings.ENVIRONMENT_VARIABLES[key] # Pulling from S3 if given a zip path project_archive_path = getattr(self.settings, 'ARCHIVE_PATH', None) if project_archive_path: self.load_remote_project_archive(project_archive_path) # Load compliled library to the PythonPath # checks if we are the slim_handler since this is not needed otherwise # https://github.com/Miserlou/Zappa/issues/776 is_slim_handler = getattr(self.settings, 'SLIM_HANDLER', False) if is_slim_handler: included_libraries = getattr(self.settings, 'INCLUDE', ['libmysqlclient.so.18']) try: from ctypes import cdll, util for library in included_libraries: try: cdll.LoadLibrary(os.path.join( os.getcwd(), library)) except OSError: print("Failed to find library...right filename?") except ImportError: print("Failed to import cytpes library") # This is a non-WSGI application # https://github.com/Miserlou/Zappa/pull/748 if not hasattr(self.settings, 'APP_MODULE') and not self.settings.DJANGO_SETTINGS: self.app_module = None wsgi_app_function = None # This is probably a normal WSGI app elif not self.settings.DJANGO_SETTINGS: # The app module self.app_module = importlib.import_module( self.settings.APP_MODULE) # The application wsgi_app_function = getattr(self.app_module, self.settings.APP_FUNCTION) self.trailing_slash = False # Django gets special treatment. else: try: # Support both for tests from zappa.ext.django_zappa import get_django_wsgi except ImportError: # pragma: no cover from django_zappa_app import get_django_wsgi # Get the Django WSGI app from our extension wsgi_app_function = get_django_wsgi( self.settings.DJANGO_SETTINGS) self.trailing_slash = True self.wsgi_app = ZappaWSGIMiddleware(wsgi_app_function)
THE SOFTWARE. """ import os from sys import platform from ctypes import Structure, POINTER, c_void_p, c_size_t, c_double, cast, cdll import numpy as np from shapely.geometry import Polygon file_path = os.path.dirname(__file__) prefix = {'win32': ''}.get(platform, 'lib') extension = {'darwin': '.dylib', 'win32': '.dll'}.get(platform, '.so') lib = cdll.LoadLibrary( os.path.join(file_path, "target/release", prefix + "polylabel" + extension)) class _InnersArray(Structure): """ Convert sequence of float lists to a C-compatible void array example: [ [[1.0, 2.0], [3.0, 4.0]], [[5.0, 6.0], [7.0, 8.0]] ] Each sequence is an interior Polygon ring """
from ctypes import cdll import os _dir_path = os.path.dirname(os.path.realpath(__file__)) _ext_path = os.path.join(_dir_path, "libsocket_ext.so") socket_ext = cdll.LoadLibrary(_ext_path)
prefix = '' ext = 'dll' prefix = {'win32': ''}.get(platform, 'lib') extension = {'darwin': '.dylib', 'win32': '.dll'}.get(platform, '.so') # Python 3 check if (version_info > (3, 0)): from subprocess import getoutput as spop py3 = True else: from subprocess import check_output as spop py3 = False try: lib = cdll.LoadLibrary( os.path.join(file_path, prefix + "lonlat_bng" + extension)) except OSError: # the Rust lib's been grafted by manylinux1 if not py3: fname = spop(["ls", fpath]).split()[0] else: fname = spop(["ls %s" % fpath]).split()[0] lib = cdll.LoadLibrary(os.path.join(file_path, ".libs", fname)) class _FFIArray(Structure): """ Convert sequence of floats to a C-compatible void array """ _fields_ = [("data", c_void_p), ("len", c_size_t)] @classmethod def from_param(cls, seq):
def __init__(self): self.lib = cdll.LoadLibrary('../obj/samplesModule.so') self.obj = self.lib.SC_new() self.lib.SC_samples.restype = POINTER(c_char_p) self.lib.SC_samples_names.restype = POINTER(c_char_p)
from ctypes import cdll, c_uint, c_void_p, c_int, c_float, c_char_p, POINTER, byref, Structure, cast #调用库 MWORKDLL = cdll.LoadLibrary("libDemo.dll") #测试strTest方法 MWORKDLL.strTest.argtype = c_char_p MWORKDLL.strTest.restype = c_char_p c = MWORKDLL.strTest("dfdsd".encode()) print("c:{}".format(c)) #测试szTest方法 print("ä¼ é€’ä¸€ç»´æ•°ç»„") INPUT = c_int * 10 data = INPUT() for i in range(10): data[i] = i MWORKDLL.szTest.argtype = (c_int * 10, c_int) MWORKDLL.szTest.restype = c_int result = MWORKDLL.szTest(data, len(data)) print('data[9] ', data[9], ' 返回值result: data[9]+5 ', result) #测试floatTest MWORKDLL.floatTest.argtype = POINTER(c_float) MWORKDLL.floatTest.restype = c_float result = MWORKDLL.floatTest(byref((c_float)(10.7))) print(result)
import numpy as np import scipy.sparse as sparse from ctypes import POINTER, c_void_p, c_int, c_char, c_double, byref, cdll # mkl = cdll.LoadLibrary("libmkl_rt.so") mkl = cdll.LoadLibrary("mkl_rt.dll") def mkl_mat_vec(A, x): """ Wrapper to Intel's SpMV (Sparse Matrix-Vector multiply) For medium-sized matrices, this is 4x faster than scipy's default implementation Stephen Becker, April 24 2014 [email protected] """ SpMV = mkl.mkl_cspblas_dcsrgemv # Dissecting the "cspblas_dcsrgemv" name: # "c" - for "c-blas" like interface (as opposed to fortran) # Also means expects sparse arrays to use 0-based indexing, which python does # "sp" for sparse # "d" for double-precision # "csr" for compressed row format # "ge" for "general", e.g., the matrix has no special structure such as symmetry # "mv" for "matrix-vector" multiply if not sparse.isspmatrix_csr(A): raise Exception("Matrix must be in csr format") (m, n) = A.shape
def _load_init_lib(name): suffix = 'so' if platform.uname()[0] != 'Darwin' else 'dylib' filename = os.path.join(_module_path(), name + '.' + suffix) return cdll.LoadLibrary(filename)
import matplotlib.pyplot as plt from numpy.linalg import norm np.random.seed(0) """ a = np.array([3, 3, 3, 0, 0, 0, 1, 2, 12]) x,y,z = np.unique(a, return_counts=True, return_index=True) print(x, y, z) print(np.repeat(x, z)) """ from ctypes import cdll import ctypes import numpy as np from numpy.ctypeslib import ndpointer cpputils = cdll.LoadLibrary("./cpputils.so") # Call this function in C++ # int * GetCuts(int node_num, int edge_num, int * nodes_from, int * nodes_to, float * weigh) def getColPairs(Xint): N = len(Xint) x = np.copy(Xint[:, 0]) y = np.copy(Xint[:, 1]) Pa = np.zeros(N, dtype=np.int32) - 1 Pb = np.zeros(N, dtype=np.int32) - 1 nums = np.arange(N, dtype=np.int32) np.random.shuffle(nums) cpputils.getColPairs.argtypes = [ ctypes.c_int, ndpointer(dtype=ctypes.c_int, shape=(N, )),
from __future__ import print_function from .tensorrt_engine import Engine from .config import Config import tensorrt as trt from onnx.backend.base import Backend, BackendRep, Device, DeviceType, namedtupledict import onnx from onnx import helper as onnx_helper from onnx import numpy_helper import numpy as np import six from .calibration import TensorBatchDataset, DatasetCalibrator, DEFAULT_CALIBRATION_ALGORITHM # HACK Should look for a better way/place to do this from ctypes import cdll, c_char_p libcudart = cdll.LoadLibrary('libcudart.so') libcudart.cudaGetErrorString.restype = c_char_p def cudaSetDevice(device_idx): ret = libcudart.cudaSetDevice(device_idx) if ret != 0: error_string = libcudart.cudaGetErrorString(ret) raise RuntimeError("cudaSetDevice: " + error_string) def count_trailing_ones(vals): count = 0 for val in reversed(vals): if val != 1: return count
#from ctypes import * from ctypes import cdll from ctypes import c_float, byref import numpy as np import traceback, os, sys, datetime, glob, copy from siman import header from siman.header import print_and_log, printlog, geo_folder, runBash from siman.classes import CalculationVasp, Structure from siman.set_functions import InputSet from siman.functions import return_atoms_to_cell, element_name_inv from siman.inout import write_xyz from siman.geo import local_surrounding, local_surrounding2 lib = cdll.LoadLibrary(os.path.dirname(__file__) + '/libfindpores.so') def create_c_array(pylist, ctype): if ctype == float: c_array = (ctypes.c_float * len(pylist))(*pylist) return c_array def find_pores(st_in, r_matrix=1.4, r_impurity=0.6, step_dec=0.05, fine=0.3, prec=0.1, calctype='central',
from gi.repository import Vte from guake.common import clamp from guake.globals import QUICK_OPEN_MATCHERS from guake.globals import TERMINAL_MATCH_EXPRS from guake.globals import TERMINAL_MATCH_TAGS log = logging.getLogger(__name__) libutempter = None try: # this allow to run some commands that requires libuterm to # be injected in current process, as: wall from atexit import register as at_exit_call from ctypes import cdll libutempter = cdll.LoadLibrary('libutempter.so.0') if libutempter is not None: # We absolutely need to remove the old tty from the utmp !!! at_exit_call(libutempter.utempter_remove_added_record) except Exception as e: libutempter = None sys.stderr.write( "[WARN] ===================================================================\n" ) sys.stderr.write("[WARN] Unable to load the library libutempter !\n") sys.stderr.write( "[WARN] Some feature might not work:\n" "[WARN] - 'exit' command might freeze the terminal instead of closing the tab\n" "[WARN] - the 'wall' command is know to work badly\n") sys.stderr.write("[WARN] Error: " + str(e) + '\n') sys.stderr.write(
""" This module wraps the dynamic library clustersearch.dylib. It defines three functions for external use: calculate_measures_as_tuple calculate_measures reseed """ from ctypes.util import find_library from ctypes import cdll from ctypes import c_uint from ctypes import c_double libclustersearch = cdll.LoadLibrary(find_library('clustersearch')) # load function reseed _reseed = libclustersearch.reseed _reseed.argtypes = [ c_uint ] # load function calculate_measures _calculate_measures = libclustersearch.calculate_measures _calculate_measures.argtypes = [ c_uint, c_uint, c_uint ] # define result struct for calculate_measure from ctypes import Structure class cluster_measure(Structure): _fields_ = [("cluster_size", c_uint), ("perimeter_size", c_uint), ("colors", c_uint), ("exits_size", c_uint),
def lib(): lib = cdll.LoadLibrary("./libdt.so") return lib
from ctypes import cdll lib = cdll.LoadLibrary('target/release/libembed.so') lib.process() print 'done!'
def _load_kmeans_lib(lib_path): """Load the underlying C/C++ KMeans library using cdll. :param lib_path: Path to the library file :return: object representing the loaded library """ try: h2o4gpu_kmeans_lib = cdll.LoadLibrary(lib_path) #Fit and Predict h2o4gpu_kmeans_lib.make_ptr_float_kmeans.argtypes = [ c_int, c_int, # verbose c_int, # seed c_int, # gpu_id c_int, # n_gpus c_size_t, # rows c_size_t, # cols c_int, # data_ord c_int, # n_clusters c_int, # max_iter c_int, # init_from_data c_float, # tol c_float_p, # data c_float_p, # centers c_void_pp, # pred_centers c_void_pp # pred_labels ] h2o4gpu_kmeans_lib.make_ptr_float_kmeans.restype = c_int h2o4gpu_kmeans_lib.make_ptr_double_kmeans.argtypes = [ c_int, c_int, # verbose c_int, # seed c_int, # gpu_id c_int, # n_gpus c_size_t, # rows c_size_t, # cols c_int, # data_ord c_int, # n_clusters c_int, # max_iter c_int, # init_from_data c_double, # tol c_double_p, # data c_double_p, # centers c_void_pp, # pred_centers c_void_pp # pred_labels ] h2o4gpu_kmeans_lib.make_ptr_double_kmeans.restype = c_int #Transform h2o4gpu_kmeans_lib.kmeans_transform_float.argtypes = [ c_int, # verbose c_int, # gpu_id c_int, # n_gpus c_size_t, # rows c_size_t, # cols c_int, # data_ord c_int, # k c_float_p, # data c_float_p, # centroids c_void_pp ] # result h2o4gpu_kmeans_lib.kmeans_transform_float.restype = c_int h2o4gpu_kmeans_lib.kmeans_transform_double.argtypes = [ c_int, # verbose c_int, # gpu_id c_int, # n_gpus c_size_t, # rows c_size_t, # cols c_int, # data_ord c_int, # k c_double_p, # data c_double_p, # centroids c_void_pp ] # result h2o4gpu_kmeans_lib.kmeans_transform_double.restype = c_int # pylint: disable=broad-except except Exception as e: print("Exception") print(e) print( '\nWarning: h2o4gpu_kmeans_lib shared object (dynamic library) %s ' 'failed to load. ' % lib_path) h2o4gpu_kmeans_lib = None return h2o4gpu_kmeans_lib
pow, object) import os import glob import numpy as np from scipy.sparse import coo_matrix from ctypes import cdll, Structure, c_int, c_double, POINTER, byref from dscribe.descriptors.descriptor import Descriptor _PATH_TO_ACSF_SO = os.path.dirname(os.path.abspath(__file__)) _ACSF_SOFILES = glob.glob("".join( [_PATH_TO_ACSF_SO, "/../libacsf/libacsf.*so*"])) _LIBACSF = cdll.LoadLibrary(_ACSF_SOFILES[0]) class ACSFObject(Structure): """Wrapper class for the ACSF C library. """ _fields_ = [('natm', c_int), ('Z', POINTER(c_int)), ('positions', POINTER(c_double)), ('nTypes', c_int), ('types', POINTER(c_int)), ('typeID', (c_int * 100)), ('nSymTypes', c_int), ('cutoff', c_double), ('n_bond_params', c_int), ('bond_params', POINTER(c_double)), ('n_bond_cos_params', c_int), ('bond_cos_params', POINTER(c_double)), ('n_ang4_params', c_int), ('ang4_params', POINTER(c_double)), ('n_ang5_params', c_int), ('ang5_params', POINTER(c_double)), ('distances', POINTER(c_double)), ('nG2', c_int),
import sys import os _arch = '64' if sys.maxsize > 2**32 else '32' _dll_path = os.path.join(os.path.abspath(os.path.dirname(__file__))) if sys.platform.startswith('darwin'): _dll_path = os.path.join(_dll_path, 'darwin64', 'libNDTable.dylib') elif sys.platform.startswith('win'): _dll_path = os.path.join(_dll_path, 'win' + _arch, 'ndtable.dll') elif sys.platform.startswith('linux'): _dll_path = os.path.join(_dll_path, 'linux' + _arch, 'libndtable.so') else: raise Exception("Unsupported platform: " + sys.platform) _ndtable = cdll.LoadLibrary(_dll_path) # PYTHON_API ModelicaNDTable_h create_table(int ndims, const int *dims, const double *data, const double **scales) { _create_table = _ndtable.create_table _create_table.argtypes = [c_int, c_void_p, c_void_p, (c_void_p * 32)] _create_table.restype = c_void_p # PYTHON_API int evaluate( # ModelicaNDTable_h table, # int ndims, # const double **params, # ModelicaNDTable_InterpMethod_t interp_method, # ModelicaNDTable_ExtrapMethod_t extrap_method, # int nvalues, # double *value); _evaluate = _ndtable.evaluate
#!/usr/bin/python from ctypes import cdll libtest = cdll.LoadLibrary("./libtest.so") libtest.test_a() libtest.test_b()
# Copyright 2010 Hardcoded Software (http://www.hardcoded.net) # This software is licensed under the "BSD" License as described in the "LICENSE" file, # which should be included with this package. The terms are also available at # http://www.hardcoded.net/licenses/bsd_license from ctypes import cdll, byref, Structure, c_char, c_char_p from ctypes.util import find_library Foundation = cdll.LoadLibrary(find_library('Foundation')) CoreServices = cdll.LoadLibrary(find_library('CoreServices')) GetMacOSStatusCommentString = Foundation.GetMacOSStatusCommentString GetMacOSStatusCommentString.restype = c_char_p FSPathMakeRefWithOptions = CoreServices.FSPathMakeRefWithOptions FSMoveObjectToTrashSync = CoreServices.FSMoveObjectToTrashSync kFSPathMakeRefDefaultOptions = 0 kFSPathMakeRefDoNotFollowLeafSymlink = 0x01 kFSFileOperationDefaultOptions = 0 kFSFileOperationOverwrite = 0x01 kFSFileOperationSkipSourcePermissionErrors = 0x02 kFSFileOperationDoNotMoveAcrossVolumes = 0x04 kFSFileOperationSkipPreflight = 0x08 class FSRef(Structure): _fields_ = [('hidden', c_char * 80)]
node_sim, node_sim_deg, node_link, node_link_deg, node_map, reverse_node_map = pickle.load(open(os.path.join('.', args.indir, pickled_file), "rb" )) reverse_map = reverse_node_map total_sim1 = sum(node_link_deg.values()) total_sim2 = sum(node_sim_deg.values()) num_elems = len(node_map) max_mu = len(node_map) elif kind == 'BLSim': edge_sim, edge_sim_deg, edge_link, edge_link_deg, edge_map, reverse_edge_map = pickle.load(open(os.path.join('.', args.indir, pickled_file), "rb" )) reverse_map = reverse_edge_map total_sim1 = sum(edge_sim_deg.values()) total_sim2 = sum(edge_link_deg.values()) num_elems = len(edge_map) max_mu = len(edge_map) lib = cdll.LoadLibrary('./bin/lib_pseudopar_baseline.so') lib.c_readDimacsFileCreateList(bytes(os.path.join('.', args.indir, meta_file), "utf8")) print('read done') lib.c_simpleInitialization() mincut_func = lib.c_getMinCutValue mincut_func.restype = c_double srcSetSize_func = lib.c_getSizeOfMinCutSet srcSetSize_func.restype = c_int c = 0 max_mu = 10 for mu in np.linspace(0, max_mu, 101): lib.c_reCreateGraph(c_int(num_elems), c_double(mu), c_double(c)) srcSet = solve_MinCut_BL(num_elems, total_sim1 + mu*total_sim2, precision = ALLOWED_ERROR, max_iters = 1000) #print_edgeset(reverse_map, srcSet)
# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. ############################################################################### import ctypes from ctypes import cdll, c_ushort, c_int from ctypes import c_double from ctypes import POINTER import math lib = cdll.LoadLibrary( '/apollo/bazel-bin/modules/tools/open_space_visualization/distance_approach_problem_wrapper_lib.so') class DistancePlanner(object): def __init__(self): self.warm_start_planner = lib.CreateHybridAPtr() self.obstacles = lib.DistanceCreateObstaclesPtr() self.result = lib.DistanceCreateResultPtr() def AddObstacle(self, ROI_distance_approach_parking_boundary): lib.AddObstacle(self.obstacles, POINTER( c_double)(ROI_distance_approach_parking_boundary)) def DistancePlan(self, sx, sy, sphi, ex, ey, ephi, XYbounds): return lib.DistancePlan(self.warm_start_planner, self.obstacles, self.result, c_double(sx), c_double(sy), c_double(sphi), c_double(ex), c_double(ey), c_double(ephi), POINTER(c_double)(XYbounds))
BTLE_MODE_OFF = 0 BTLE_MODE_FIXEDCHANNEL = 1 BTLE_MODE_FOLLOW_STATIC = 2 BTLE_MODE_FOLLOW_DYNAMIC = 3 DEMOD_BYTES_META_LEN = 10 RETURN_OK = 0 RETURN_ERROR = 1 FILENAME_LIB = "libhackrf_wrapper.so" FILENAME_LIB_ABSOLUTE = os.path.join(os.path.dirname(__file__), "./src/build/" + FILENAME_LIB) try: dll = cdll.LoadLibrary(FILENAME_LIB_ABSOLUTE) except Exception as ex: logger.warning("Could not find wrapper lib: %s", FILENAME_LIB_ABSOLUTE) print(ex) sys.exit(1) class HackRFBoard(object): """ Wrapper around bluehack customized libhackrf """ def __init__(self): self._ct_rcv_data = create_string_buffer(1024) self._ct_rcv_data_len = c_int() def open(self):
def free(self): free = cdll.LoadLibrary('libc.dylib').free free.argtypes = [c_void_p] return free