class TrackIR_Signature_Data(ctypes.Structure): """ This is information about the DLL returned by TrackIRDLL.NP_GetSignature() This struct-equivalent is to replicate the 'struct tir_signature' that is passed to the NP_GetSignature(struct tir_signature *sig) function in the DLL It must exactly match the C struct: pragma pack(1) struct tir_data{ char DllSignature[200]; char AppSignature[200]; }; See the python ctypes.Structure documentation for information about _pack_ and _fields_ """ _pack_ = 1 _fields_ = [ ("_DllSignature", ctypes.ARRAY(ctypes.c_char, 200)), ("_AppSignature", ctypes.ARRAY(ctypes.c_char, 200)) ] @property def DllSignature(self) -> str: return self._DllSignature.decode('utf-8') @property def AppSignature(self) -> str: return self._AppSignature.decode('utf-8')
class psrCoord(ctypes.Structure): """ Struct repr of psrCoord field in ChimeMetadata.""" _fields_ = [ ("ra", ctypes.ARRAY(ctypes.c_float, 10)), ("dec", ctypes.ARRAY(ctypes.c_float, 10)), ("scaling", ctypes.ARRAY(ctypes.c_uint32, 10)), ]
def _test8_0(): ssp = extern('sparse_scal_prod', double_t, [ double_t, int32_t, pointer(int32_t), pointer(double_t), int32_t, pointer(int32_t), pointer(double_t) ]) acc = variable('acc') n0 = variable('n0') idx0 = variable('idx0') val0 = variable('val0') n1 = variable('n1') idx1 = variable('idx1') val1 = variable('val1') ssp = function( 'sparse_scal_prod', [acc, n0, idx0, val0, n1, idx1, val1], [ double_t, int32_t, pointer(int32_t), pointer(double_t), int32_t, pointer(int32_t), pointer(double_t) ], condition((n0 > 0) & (n1 > 0), on_true=(condition( idx0[0] < idx1[0], ssp(acc, n0 - 1, idx0.displ(1), val0.displ(1), n1, idx1, val1), condition( idx0[0] > idx1[0], ssp(acc, n0, idx0, val0, n1 - 1, idx1.displ(1), val1.displ(1)), ssp(val0[0] * val1[0], n0 - 1, idx0.displ(1), val0.displ(1), n1 - 1, idx1.displ(1), val1.displ(1))))), on_false=acc)) t = llvm_compile_closed(ssp, "test") z = t() llvm_dump_module() import ctypes v0 = [ ctypes.ARRAY(ctypes.c_int32, 16)(0, 1), ctypes.ARRAY(ctypes.c_double, 16)(0.5, 0.5) ] v1 = [ ctypes.ARRAY(ctypes.c_int32, 16)(1, 2), ctypes.ARRAY(ctypes.c_double, 16)(0.1, 1.0) ] print z(0., 2, ctypes.pointer(v0[0]), ctypes.pointer(v0[1]), 2, ctypes.pointer(v1[0]), ctypes.pointer(v1[1]))
class Header(ctypes.BigEndianStructure): _fields_ = [ ("magic", ctypes.ARRAY(ctypes.c_char, 4)), ("payload_size", ctypes.c_uint32), ("header_md5", ctypes.ARRAY(ctypes.c_ubyte, 8)), ("etl", ctypes.ARRAY(ctypes.c_uint8, 7)), # always zero ("unused_1", ctypes.c_char), ("password_len", ctypes.c_uint16), ("padding_len", ctypes.c_uint16), ("unused_2", ctypes.ARRAY(ctypes.c_ubyte, 4)), ("plaintext_md5", ctypes.ARRAY(ctypes.c_ubyte, 16)) ]
class SkeletonData(ctypes.Structure): """Contains data that characterizes a skeleton.""" _fields_ = [('eTrackingState', SkeletonTrackingState), ('dwTrackingID', ctypes.c_uint32), ('dwEnrollmentIndex', ctypes.c_uint32), ('dwUserIndex', ctypes.c_uint32), ('Position', Vector), ('SkeletonPositions', ctypes.ARRAY(Vector, NUI_SKELETON_POSITION_COUNT)), ('eSkeletonPositionTrackingState', ctypes.ARRAY(JointTrackingState, NUI_SKELETON_POSITION_COUNT)), ('Quality', SkeletonQuality), ] def __repr__(self): return '<Tracking: {0}, ID: {1}, Position: {2}>'.format(self.eTrackingState, self.dwTrackingID, self.Position)
def squares(in_array, out_array): global squares n = len(in_array) array = ct.c_float * n _squares.argtypes = ct.ARRAY(ct.c_float, n), ct.c_int, \ ct.ARRAY(ct.c_float, n) out = array(*out_array) _squares(array(*in_array), n, out) for i in range(n): out_array[i] = out[i]
class FntHeader(ctypes.Structure): _fields_ = [('signature', ctypes.ARRAY(ctypes.c_uint8, 12)), ('verlo0', ctypes.c_uint8), ('verhi0', ctypes.c_uint8), ('verhi1', ctypes.c_uint8), ('verlo1', ctypes.c_uint8), ('pcx_offset', ctypes.c_uint32), ('txt_offset', ctypes.c_uint32), ('txt_len', ctypes.c_uint32), ('BLANK', ctypes.ARRAY(ctypes.c_char, 40))] _pcx = None _conf = None def __repr__(self): out = f"{self.__class__.__name__}(" for k, _ in self._fields_: out += f"{k}={getattr(self, k)}, " return out[:-2] + ")"
def run_case_1_from_DLL_obj(): lib = cdll.LoadLibrary('./TCNN_lib.so') argv = [ WIN_BIN_OPT_FUNC, "--steps", "2000", "--step_len", "0.1", "--alpha", "0.3", "--chaotic_coeff", "3", "--chaotic_reduce", "0.9995", "--function", "1", "--init_cond", "0,-2.8" ] amount_strs = len(argv) max_len = len(max(argv, key=len)) s = [ctypes.create_string_buffer(max_len) for i in range(amount_strs)] results = (ctypes.c_char_p * amount_strs)(*map(ctypes.addressof, s)) for i in range(len(argv)): results[i] = argv[i] optFunc = lib.optFuncCreateDLL() lib.optFuncSetInitialConditionByArgvDLL(optFunc, amount_strs, results) lib.optFuncRunOptimizationDLL(optFunc) # lib.optFuncWriteResultDLL(optFunc, "DLL_opt_func_result.log") rows = lib.optFunctGetResultRows(optFunc) columns = lib.optFunctGetResultColumns(optFunc) data = ctypes.ARRAY(ctypes.c_double, rows * columns)() lib.optFuncTakeResultDLL(optFunc, data) plt.plot(data[:rows], data[rows:]) plt.show()
def get_ctypes_type(debug_type): if isinstance(debug_type, debuginfo.DebugBaseType): return debug_type_name_mapping[debug_type.name] elif isinstance(debug_type, debuginfo.DebugPointerType): if isinstance(debug_type.pointed_type, debuginfo.DebugStructType): # TODO: treat struct pointers as void pointers for now. # TODO: fix this? return ctypes.c_voidp else: return ctypes.POINTER(get_ctypes_type(debug_type.pointed_type)) elif isinstance(debug_type, debuginfo.DebugArrayType): element_type = get_ctypes_type(debug_type.element_type) return ctypes.ARRAY(element_type, debug_type.size) elif debug_type is None: return elif isinstance(debug_type, type): mapping = {int: ctypes.c_int, float: ctypes.c_double} return mapping[debug_type] elif isinstance(debug_type, ir.BasicTyp): mapping = { ir.f32: ctypes.c_float, ir.f64: ctypes.c_double, ir.i32: ctypes.c_int32, ir.i64: ctypes.c_int64, # TODO: which one of 32 and 64 is int? } return mapping[debug_type] else: # pragma: no cover raise NotImplementedError(str(debug_type) + str(type(debug_type)))
def __setstate__(self, state): """Pickle deserialization API This method is called by the pickle module to populate a deserialized object's state after it has been created. """ self.databuffersize = state['databuffersize'] self.p_storageheader.contents = state['storageheader'] self.p_standardheader.contents = state['standardheader'] self.headerextra = state['headerextra'] self.p_extendedheader.contents = state['extendedheader'] # - populate databuffer databuffer = ctypes.ARRAY(ctypes.c_uint8, self.datasize)() for index, byte in enumerate(state['databuffer']): databuffer[index] = byte self.databuffer = databuffer # - populate headerbuffer for index, byte in enumerate(state['headerbuffer']): self.headerbuffer[index] = byte # - This is required because we are not calling # dlt_message_init() so we do not need to call # dlt_message_free() self.initialized_as_object = False
class osockaddr(ctypes.Structure): """C like structure for osockaddr Stevens 3.5""" _fields_ = [ ('sa_len', ctypes.c_uint8), ('sa_family', ctypes.c_uint8), ('sa_data' , ctypes.ARRAY( ctypes.c_char, 14) ) ]
def read_buffer(filename): ''' IIO: float_buffer, w, h, nch = read_buffer(filename) ''' from ctypes import c_int, c_float, c_void_p, POINTER, cast, byref, c_char, memmove, create_string_buffer, sizeof iioread = libiio.iio_read_image_float_vec w = c_int() h = c_int() nch = c_int() iioread.restype = c_void_p # it's like this tptr = iioread( str(filename).encode('ascii'), byref(w), byref(h), byref(nch)) if (tptr == None): raise IOError('PIIO: the file %s cannot be read' % (filename)) c_float_p = POINTER(c_float) # define a new type of pointer ptr = cast(tptr, c_float_p) #print w,h,nch #nasty read data into array using buffer copy #http://stackoverflow.com/questions/4355524/getting-data-from-ctypes-array-into-numpy #http://docs.scipy.org/doc/numpy/reference/generated/numpy.frombuffer.html N = h.value * w.value * nch.value # data = create_string_buffer(N * sizeof(c_float)) data = ctypes.ARRAY(ctypes.c_float, N)() memmove(data, ptr, N * sizeof(c_float)) # free the memory libiio.freemem(ptr) return data, w.value, h.value, nch.value
def do_get_coincidence_counters(self): #OK! """ Retreive Coincidence Counters. Retreives the most recent values of the built-in coincidence counters. The coincidence counters are not accumulated, i.e. the counter values for the last exposure (see TDC_setExposureTime ) are returned. The array contains count rates for all 8 channels, and rates for two, three, and fourfold coincidences of events detected on different channels out of the first 4. Events are coincident if they happen within the coincidence window (see TDC_setCoincidenceWindow ). Output: Counter Values. The array must have at least 19 elements. The Counters come in the following order: 1, 2, 3, 4, 5, 6, 7, 8, 1/2, 1/3, 1/4, 2/3, 2/4, 3/4, 1/2/3, 1/2/4, 1/3/4, 2/3/4, 1/2/3/4 """ data = ctypes.ARRAY(ctypes.c_int32, 19)() ans = self.qutools_dll.TDC_getCoincCounters(ctypes.byref(data)) if ans != 0: return self.err_dict[ans] else: dat = np.zeros(19) for idx, val in enumerate(data): dat[idx] = val return dat
class LibCBM_Error(ctypes.Structure): """Wrapper for low level C/C++ LibCBM structure of the same name. Stores string error message when they occur in library functions. """ _fields_ = [("Error", ctypes.c_int), ("Message", ctypes.ARRAY(ctypes.c_byte, 1000))] def __init__(self): setattr(self, "Error", 0) setattr(self, "Message", ctypes.ARRAY(ctypes.c_byte, 1000)()) def getError(self): """Gets the error code from an error returned by a library function. If no error occurred this is zero. """ code = getattr(self, "Error") return code def getErrorMessage(self): """Gets the error message from an error returned by a library function. If no error occurred this is an empty string. """ msg = ctypes.cast(getattr(self, "Message"), ctypes.c_char_p).value return msg
def __init__(self, data): """Android Bootloader image Arguments: data(str): Binary data from the image file. """ self.data = data self.header = bootloader_images_header.from_buffer_copy(data) if self.magic != BOOTLDR_MAGIC: log.error("Incorrect magic (%r, expected %r)" % (self.magic, BOOTLDR_MAGIC)) if (self.bootldr_size > len(data)): log.warn_once( "Bootloader is supposed to be %#x bytes, only have %#x", self.bootldr_size, len(data)) if (self.num_images >= 0x100): old = self.num_images self.num_images = 1 log.warn_once( "Bootloader num_images (%#x) appears corrupted, truncating to 1", old) imgarray = ctypes.ARRAY(img_info, self.num_images) self.img_info = imgarray.from_buffer_copy(data, ctypes.sizeof(self.header))
def _test8(): ssp = extern('sparse_scal_prod', double_t, [ double_t, int32_t, pointer(int32_t), pointer(double_t), int32_t, pointer(int32_t), pointer(double_t) ]) acc = variable('acc') n0 = variable('n0') idx0 = variable('idx0') val0 = variable('val0') n1 = variable('n1') idx1 = variable('idx1') val1 = variable('val1') ssp = function( 'sparse_scal_prod', [acc, n0, idx0, val0, n1, idx1, val1], [ double_t, int32_t, pointer(int32_t), pointer(double_t), int32_t, pointer(int32_t), pointer(double_t) ], condition((n0 > 0) & (n1 > 0), on_true=(condition( idx0[0] < idx1[0], ssp(acc, n0 - 1, idx0.displ(1), val0.displ(1), n1, idx1, val1), condition( idx0[0] > idx1[0], ssp(acc, n0, idx0, val0, n1 - 1, idx1.displ(1), val1.displ(1)), ssp(val0[0] * val1[0], n0 - 1, idx0.displ(1), val0.displ(1), n1 - 1, idx1.displ(1), val1.displ(1))))), on_false=acc)) z = llvm_compile(ssp, {})() llvm_dump_module() import ctypes v0 = (ctypes.ARRAY(ctypes.c_int32, 16)(), ctypes.ARRAY(ctypes.c_double, 16)()) v1 = (ctypes.ARRAY(ctypes.c_int32, 16)(), ctypes.ARRAY(ctypes.c_double, 16)()) print v0, v1 return z(0., 1, v0[0], v0[1], 1, v1[0], v1[1])
def test_skeleton_data(self): pos_arr = ctypes.ARRAY(Vector, JointId.count.value)() pos_arr[0] = Vector(2,4,6,8) joint_arr = ctypes.ARRAY(JointTrackingState, JointId.count.value)() joint_arr[0] = JointTrackingState.inferred tests = [('tracking_state', 'eTrackingState', SkeletonTrackingState.tracked), ('tracking_id', 'dwTrackingID', 1), ('enrollment_index', 'dwEnrollmentIndex', 1), ('user_index', 'dwUserIndex', 1), ('position', 'Position', Vector(1, 2, 3, 4)), ('skeleton_positions', 'SkeletonPositions', pos_arr), ('skeleton_position_tracking_states', 'eSkeletonPositionTrackingState', joint_arr), ('skeleton_quality', 'Quality', SkeletonQuality.clipped_bottom), ] self.interop_prop_test(SkeletonData(), tests)
def ArrayType(cl, c): n = '%s_Array_%u' % (cl.__name__, c) ncl = PyMUICType.__ary_dict.get(n) if not ncl: ncl = _ct.ARRAY(cl, c) ncl = type(n, (PyMUICArrayType, ncl), {'_length_': c, '_type_': cl}) PyMUICType.__ary_dict[n] = ncl return ncl
class VTermScreenCell_s(ctypes.Structure): _fields_ = ( ('chars', ctypes.ARRAY(ctypes.c_uint32, VTERM_MAX_CHARS_PER_CELL)), ('width', ctypes.c_char), ('attrs', VTermScreenCellAttrs_s), ('fg', VTermColor_s), ('bg', VTermColor_s), )
class SkeletonFrame(ctypes.Structure): _pack_ = 16 _fields_ = [ ('liTimeStamp', ctypes.c_longlong), ('dwFrameNumber', ctypes.c_uint32), ('Quality', SkeletonFrameQuality), ('vFloorClipPlane', Vector), ('vNormalToGravity', Vector), ('SkeletonData', ctypes.ARRAY(SkeletonData, NUI_SKELETON_COUNT)), ] def get_timestamp(self): return self.liTimeStamp def set_timestamp(self, value): self.liTimeStamp = value timestamp = property(get_timestamp, set_timestamp) def get_frame_number(self): return self.dwFrameNumber def set_frame_number(self, value): self.dwFrameNumber = value frame_number = property(get_frame_number, set_frame_number) def get_quality(self): return self.Quality def set_quality(self, value): self.Quality = value quality = property(get_quality, set_quality) def get_floor_clip_plane(self): return self.vFloorClipPlane def set_floor_clip_plane(self, value): self.vFloorClipPlane = value floor_clip_plane = property(get_floor_clip_plane, set_floor_clip_plane) def get_normal_to_gravity(self): return self.vNormalToGravity def set_normal_to_gravity(self, value): self.vNormalToGravity = value normal_to_gravity = property(get_normal_to_gravity, set_normal_to_gravity) def get_skeleton_data(self): return self.SkeletonData def set_skeleton_data(self, value): self.SkeletonData = value skeleton_data = property(get_skeleton_data, set_skeleton_data)
class SndHeader(ctypes.Structure): _fields_ = [ ('signature', ctypes.ARRAY(ctypes.c_uint8,12)), ('verlo0',ctypes.c_uint8), ('verhi0',ctypes.c_uint8), ('verhi1',ctypes.c_uint8), ('verlo1',ctypes.c_uint8), ('sounds_count',ctypes.c_uint32), ('first_subheader_offset',ctypes.c_uint32), ('BLANK', ctypes.ARRAY(ctypes.c_uint8,488)) ] def __repr__(self): out = f"{self.__class__.__name__}(" for k,_ in self._fields_: out += f"{k}={getattr(self, k)}, " return out[:-2] + ")"
class SFFHeader(ctypes.Structure): _fields_ = [('signature', ctypes.ARRAY(ctypes.c_char,12)), ('verhi', ctypes.c_uint8), ('verlo', ctypes.c_uint8), ('verlo2', ctypes.c_uint8), ('verlo3', ctypes.c_uint8), ('num_groups', ctypes.c_long), ('num_images', ctypes.c_long), ('first_offset', ctypes.c_long), ('subheader_size', ctypes.c_long), ('is_shared', ctypes.c_bool), ('reserved', ctypes.ARRAY(ctypes.c_uint8,3)), ('BLANK', ctypes.ARRAY(ctypes.c_uint8,476))] def __repr__(self): out = f"{self.__class__.__name__}(" for k,_ in self._fields_: out += f"{k}={getattr(self, k)}, " return out[:-2] + ")"
class sockaddr_in(ctypes.Structure): """C like strcuture for sockaddr_in (IPV4) Steven 6.4""" _fields_ = [ ('sin_len' , ctypes.c_ubyte), ('sin_family' , ctypes.c_ubyte), ('sin_port' , ctypes.c_ushort), ('sin_addr' , in_addr ), ('sin_zero' , ctypes.ARRAY(ctypes.c_char, 8)) ]
def __getitem__(self, item): if isinstance(item, six.string_types): if hasattr(self._object, item): v = getattr(self._object, item) if isinstance(v, ctypes.Array) and \ isinstance(v, ctypes.ARRAY(ctypes.c_byte, len(v))): return ctypes.cast(v, ctypes.c_char_p).value return v return None
class SkeletonFrame(ctypes.Structure): _pack_ = 16 _fields_ = [('liTimeStamp', ctypes.c_longlong), ('dwFrameNumber', ctypes.c_uint32), ('Quality', SkeletonFrameQuality), ('vFloorClipPlane', Vector), ('vNormalToGravity', Vector), ('SkeletonData', ctypes.ARRAY(SkeletonData, NUI_SKELETON_COUNT)), ]
def __getattr__(self, item): if item == '_object': raise AttributeError() if hasattr(self._object, item): v = getattr(self._object, item) if isinstance(v, ctypes.Array) and \ isinstance(v, ctypes.ARRAY(ctypes.c_byte, len(v))): return ctypes.cast(v, ctypes.c_char_p).value.decode() return v raise AttributeError()
def findKNN(bcode_int64s): resultIDs = ctypes.ARRAY(ctypes.c_int, 50)() codearray = ctypes.c_ulonglong * 4 bcodes = codearray(bcode_int64s[0], bcode_int64s[1], bcode_int64s[2], bcode_int64s[3]) so.bkmKNeighbors(resultIDs, K, bcodes) #dump(resultIDs) return resultIDs, [ image_path_dict[resultIDs[i]] for i in range(len(resultIDs)) ], [image_label_dict[resultIDs[i]] for i in range(len(resultIDs))]
def _construct_c_structures_helper(self, ctype, size): # Return a pointer to the C variable if size is NA. if size is NA: return ctypes.pointer(ctype()) # Return an array of the C variable otherwise. elif not np.iterable(size): return (ctype * size)() else: for i in size: ctype = ctypes.ARRAY(ctype, i) return ctype()
def __init__(self, data): """Android Bootloader image Arguments: data(str): Binary data from the image file. """ self.data = data self.header = bootloader_images_header.from_buffer_copy(data) imgarray = ctypes.ARRAY(img_info, self.header.num_images) self.img_info = imgarray.from_buffer_copy(data, ctypes.sizeof(self.header))
def read_tiled_buffers(filename): ''' IIO: float_buffer, w, h, nch = read_buffer(filename) ''' from ctypes import c_int, c_float, c_void_p, POINTER, cast, byref, c_char, memmove, create_string_buffer, sizeof w = c_int() h = c_int() nch = c_int() libiio.iio_read_image_float_vec.restype = c_void_p # it's like this tptr = libiio.iio_read_image_float_vec( str(filename).encode('ascii'), byref(w), byref(h), byref(nch)) if (tptr == None): raise IOError('PIIO: the file %s cannot be read' % (filename)) c_float_p = POINTER(c_float) # define a new type of pointer ptr = cast(tptr, c_float_p) #print w,h,nch w, h, nch = w.value, h.value, nch.value # compute min and max of the data vmin = c_float() vmax = c_float() N = w * h * nch libiio.minmax.restype = c_void_p # it's like this libiio.minmax.argtypes = [c_float_p, c_int, c_float_p, c_float_p] libiio.minmax(ptr, N, byref(vmin), byref(vmax)) vmin, vmax = vmin.value, vmax.value tiles = [] out_nch = min(nch, 4) if (nch != out_nch): print( "piio_read: the input image have %d channels, only the first 4 are loaded\n" % nch) # generate several buffers, one for each tile for y in range(0, h, 1024): for x in range(0, w, 1024): ww = min(w - x, 1024) hh = min(h - y, 1024) N = ww * hh * out_nch # generate the interlan memory to copy the tile data = ctypes.ARRAY(ctypes.c_float, N)() libiio.copy_tile(ptr, w, h, nch, data, x, y, ww, hh, out_nch) # only allow up to 4 channels tiles.append( [data, x, y, ww, hh, out_nch, -1]) # -1 (the last field is a placeholder for the textureID) # free the memory libiio.freemem(ptr) return (tiles, w, h, out_nch, vmin, vmax)