Python ctypes.c_uint8() Examples
The following are 30
code examples of ctypes.c_uint8().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
ctypes
, or try the search function
.
Example #1
Source File: smbus.py From Adafruit_Python_PureIO with MIT License | 7 votes |
def read_byte_data(self, addr, cmd): """Read a single byte from the specified cmd register of the device.""" assert ( self._device is not None ), "Bus must be opened before operations are made against it!" # Build ctypes values to marshall between ioctl and Python. reg = c_uint8(cmd) result = c_uint8() # Build ioctl request. request = make_i2c_rdwr_data( [ (addr, 0, 1, pointer(reg)), # Write cmd register. (addr, I2C_M_RD, 1, pointer(result)), # Read 1 byte as result. ] ) # Make ioctl call and return result data. ioctl(self._device.fileno(), I2C_RDWR, request) return result.value
Example #2
Source File: test_dtype.py From predictive-maintenance-using-machine-learning with Apache License 2.0 | 6 votes |
def test_union_packed(self): class Struct(ctypes.Structure): _fields_ = [ ('one', ctypes.c_uint8), ('two', ctypes.c_uint32) ] _pack_ = 1 class Union(ctypes.Union): _pack_ = 1 _fields_ = [ ('a', ctypes.c_uint8), ('b', ctypes.c_uint16), ('c', ctypes.c_uint32), ('d', Struct), ] expected = np.dtype(dict( names=['a', 'b', 'c', 'd'], formats=['u1', np.uint16, np.uint32, [('one', 'u1'), ('two', np.uint32)]], offsets=[0, 0, 0, 0], itemsize=ctypes.sizeof(Union) )) self.check(Union, expected)
Example #3
Source File: test_dtype.py From recruit with Apache License 2.0 | 6 votes |
def test_pointer(self): p_uint8 = ctypes.POINTER(ctypes.c_uint8) assert_raises(TypeError, np.dtype, p_uint8)
Example #4
Source File: test_dtype.py From recruit with Apache License 2.0 | 6 votes |
def test_union_packed(self): class Struct(ctypes.Structure): _fields_ = [ ('one', ctypes.c_uint8), ('two', ctypes.c_uint32) ] _pack_ = 1 class Union(ctypes.Union): _pack_ = 1 _fields_ = [ ('a', ctypes.c_uint8), ('b', ctypes.c_uint16), ('c', ctypes.c_uint32), ('d', Struct), ] expected = np.dtype(dict( names=['a', 'b', 'c', 'd'], formats=['u1', np.uint16, np.uint32, [('one', 'u1'), ('two', np.uint32)]], offsets=[0, 0, 0, 0], itemsize=ctypes.sizeof(Union) )) self.check(Union, expected)
Example #5
Source File: smbus.py From Adafruit_Python_PureIO with MIT License | 6 votes |
def make_i2c_rdwr_data(messages): """Utility function to create and return an i2c_rdwr_ioctl_data structure populated with a list of specified I2C messages. The messages parameter should be a list of tuples which represent the individual I2C messages to send in this transaction. Tuples should contain 4 elements: address value, flags value, buffer length, ctypes c_uint8 pointer to buffer. """ # Create message array and populate with provided data. msg_data_type = i2c_msg * len(messages) msg_data = msg_data_type() for i, message in enumerate(messages): msg_data[i].addr = message[0] & 0x7F msg_data[i].flags = message[1] msg_data[i].len = message[2] msg_data[i].buf = message[3] # Now build the data structure. data = i2c_rdwr_ioctl_data() data.msgs = msg_data data.nmsgs = len(messages) return data # Create an interface that mimics the Python SMBus API.
Example #6
Source File: messages.py From olympe with BSD 3-Clause "New" or "Revised" License | 6 votes |
def _ar_arsdk_encode_type_info(cls, ar_argtype): arsdk_encode_type_info_map = { arsdkparser.ArArgType.I8: (od.ARSDK_ARG_TYPE_I8, "i8", ctypes.c_int8), arsdkparser.ArArgType.U8: (od.ARSDK_ARG_TYPE_U8, "u8", ctypes.c_uint8), arsdkparser.ArArgType.I16: (od.ARSDK_ARG_TYPE_I16, "i16", ctypes.c_int16), arsdkparser.ArArgType.U16: (od.ARSDK_ARG_TYPE_U16, "u16", ctypes.c_uint16), arsdkparser.ArArgType.I32: (od.ARSDK_ARG_TYPE_I32, "i32", ctypes.c_int32), arsdkparser.ArArgType.U32: (od.ARSDK_ARG_TYPE_U32, "u32", ctypes.c_uint32), arsdkparser.ArArgType.I64: (od.ARSDK_ARG_TYPE_I64, "i64", ctypes.c_int64), arsdkparser.ArArgType.U64: (od.ARSDK_ARG_TYPE_U64, "u64", ctypes.c_uint64), arsdkparser.ArArgType.FLOAT: (od.ARSDK_ARG_TYPE_FLOAT, "f32", ctypes.c_float), arsdkparser.ArArgType.DOUBLE: (od.ARSDK_ARG_TYPE_DOUBLE, "f64", ctypes.c_double), arsdkparser.ArArgType.STRING: (od.ARSDK_ARG_TYPE_STRING, "cstr", od.char_pointer_cast), arsdkparser.ArArgType.ENUM: (od.ARSDK_ARG_TYPE_ENUM, "i32", ctypes.c_int32), } return arsdk_encode_type_info_map[ar_argtype]
Example #7
Source File: test_dtype.py From recruit with Apache License 2.0 | 6 votes |
def test_large_packed_structure(self): class PackedStructure(ctypes.Structure): _pack_ = 2 _fields_ = [ ('a', ctypes.c_uint8), ('b', ctypes.c_uint16), ('c', ctypes.c_uint8), ('d', ctypes.c_uint16), ('e', ctypes.c_uint32), ('f', ctypes.c_uint32), ('g', ctypes.c_uint8) ] expected = np.dtype(dict( formats=[np.uint8, np.uint16, np.uint8, np.uint16, np.uint32, np.uint32, np.uint8 ], offsets=[0, 2, 4, 6, 8, 12, 16], names=['a', 'b', 'c', 'd', 'e', 'f', 'g'], itemsize=18)) self.check(PackedStructure, expected)
Example #8
Source File: test_dtype.py From predictive-maintenance-using-machine-learning with Apache License 2.0 | 6 votes |
def test_large_packed_structure(self): class PackedStructure(ctypes.Structure): _pack_ = 2 _fields_ = [ ('a', ctypes.c_uint8), ('b', ctypes.c_uint16), ('c', ctypes.c_uint8), ('d', ctypes.c_uint16), ('e', ctypes.c_uint32), ('f', ctypes.c_uint32), ('g', ctypes.c_uint8) ] expected = np.dtype(dict( formats=[np.uint8, np.uint16, np.uint8, np.uint16, np.uint32, np.uint32, np.uint8 ], offsets=[0, 2, 4, 6, 8, 12, 16], names=['a', 'b', 'c', 'd', 'e', 'f', 'g'], itemsize=18)) self.check(PackedStructure, expected)
Example #9
Source File: device.py From py-uio with MIT License | 6 votes |
def fill( rgn, length=None, offset=0, value=0 ): if value not in range(256): raise ValueError( "invalid fill value" ) if length is None: length = rgn.mappable # map ctypes instance (does all necessary error checking) mem = (ubyte * length).from_buffer( rgn._mmap, offset ) ctypes.memset( mem, value, length ) # write data into region at given offset
Example #10
Source File: arithmetic.py From grimoire with GNU Affero General Public License v3.0 | 6 votes |
def mutate_seq_8_bit_arithmetic_array(data, func, default_info, skip_null=False, effector_map=None, set_arith_max=None): if not set_arith_max: set_arith_max = AFL_ARITH_MAX for i in range(0, len(data)): if effector_map: if not effector_map[i]: continue if skip_null and data[i] == 0x00: continue for j in range(1, set_arith_max + 1): r = data[i] ^ (data[i] + j) if is_not_bitflip(ctypes.c_uint8(r).value): data[i] = (data[i] + j) & 0xff func(data.tostring(), default_info) data[i] = (data[i] - j) & 0xff r = data[i] ^ (data[i] - j) if is_not_bitflip(ctypes.c_uint8(r).value): data[i] = (data[i] - j) & 0xff func(data.tostring(), default_info) data[i] = (data[i] + j) & 0xff
Example #11
Source File: test_hdrhistogram.py From HdrHistogram_py with Apache License 2.0 | 6 votes |
def check_zz_identity(src_array, int_type, min_nz_index, max_nz_index, total_count, offset): dst_len = (sizeof(int_type) + 1) * ARRAY_SIZE dst = (c_uint8 * (offset + dst_len))() varint_len = encode(addressof(src_array), ARRAY_SIZE, sizeof(int_type), addressof(dst) + offset, dst_len) varint_string = string_at(dst, varint_len + offset) dst_array = (int_type * ARRAY_SIZE)() res = decode(varint_string, offset, addressof(dst_array), ARRAY_SIZE, sizeof(int_type)) assert res['total'] == total_count if total_count: assert res['min_nonzero_index'] == min_nz_index assert res['max_nonzero_index'] == max_nz_index for index in range(ARRAY_SIZE): assert dst_array[index] == src_array[index] # A large positive value that can fit 16-bit signed
Example #12
Source File: avfoundation_capture.py From IkaLog with Apache License 2.0 | 6 votes |
def _init_library(self): self.dest_buffer = np.zeros((720, 1280, 4), np.uint8) libavf_dll = os.path.join('lib', 'libavf_ctypes.so') ctypes.cdll.LoadLibrary(libavf_dll) self.dll = ctypes.CDLL(libavf_dll) self.dll.initialize.argtypes = None self.dll.initialize.restype = None self.dll.deinitialize.argtypes = None self.dll.deinitialize.restype = None self.dll.read_frame.argtypes = [ ndpointer(ctypes.c_uint8, flags="C_CONTIGUOUS")] self.dll.read_frame.restype = None self.dll.select_capture_source.argtypes = [ctypes.c_int] self.dll.select_capture_source.restype = None self.dll.get_source_count.argtypes = None self.dll.get_source_count.restype = ctypes.c_int self.dll.get_source_name.argtypes = [ctypes.c_int] self.dll.get_source_name.restype = ctypes.c_char_p
Example #13
Source File: gps_time.py From rtkbase with GNU Affero General Public License v3.0 | 6 votes |
def is_valid(self, msg): """Count and verify the checksum of a ubx message. msg is a list of hex values""" to_check = msg[2:-2] ck_a = ctypes.c_uint8(0) ck_b = ctypes.c_uint8(0) for num in to_check: byte = ctypes.c_uint8(num) ck_a.value = ck_a.value + byte.value ck_b.value = ck_b.value + ck_a.value if (ck_a.value, ck_b.value) == (ctypes.c_uint8(msg[-2]).value, ctypes.c_uint8(msg[-1]).value): return True else: return False
Example #14
Source File: gps_time.py From rtkbase with GNU Affero General Public License v3.0 | 6 votes |
def unpack(self, msg): """Extract the actual time from the message""" datetime = [] # unpack year byte1 = ctypes.c_uint8(msg[18]) byte2 = ctypes.c_uint8(msg[19]) year = ctypes.c_uint16(byte2.value << 8 | byte1.value).value datetime.append(year) # unpack month, day, hour, minute, second for i in range(20, 25): datetime.append(msg[i]) date = datetime[:3] time = datetime[3:] return date, time
Example #15
Source File: utils.py From debin with Apache License 2.0 | 6 votes |
def adapt_int_width(n, width, signed=True): n = int(n) if width == 1: result = n elif width == 2: result = n elif width == 4: result = ctypes.c_int8(n).value if signed else ctypes.c_uint8(n).value elif width == 8: result = ctypes.c_int8(n).value if signed else ctypes.c_uint8(n).value elif width == 16: result = ctypes.c_int16(n).value if signed else ctypes.c_uint16(n).value elif width == 32: result = ctypes.c_int32(n).value if signed else ctypes.c_uint32(n).value elif width == 64: result = ctypes.c_int64(n).value if signed else ctypes.c_uint64(n).value else: result = n return result
Example #16
Source File: test_dtype.py From Mastering-Elasticsearch-7.0 with MIT License | 6 votes |
def test_union_packed(self): class Struct(ctypes.Structure): _fields_ = [ ('one', ctypes.c_uint8), ('two', ctypes.c_uint32) ] _pack_ = 1 class Union(ctypes.Union): _pack_ = 1 _fields_ = [ ('a', ctypes.c_uint8), ('b', ctypes.c_uint16), ('c', ctypes.c_uint32), ('d', Struct), ] expected = np.dtype(dict( names=['a', 'b', 'c', 'd'], formats=['u1', np.uint16, np.uint32, [('one', 'u1'), ('two', np.uint32)]], offsets=[0, 0, 0, 0], itemsize=ctypes.sizeof(Union) )) self.check(Union, expected)
Example #17
Source File: test_dtype.py From Mastering-Elasticsearch-7.0 with MIT License | 6 votes |
def test_large_packed_structure(self): class PackedStructure(ctypes.Structure): _pack_ = 2 _fields_ = [ ('a', ctypes.c_uint8), ('b', ctypes.c_uint16), ('c', ctypes.c_uint8), ('d', ctypes.c_uint16), ('e', ctypes.c_uint32), ('f', ctypes.c_uint32), ('g', ctypes.c_uint8) ] expected = np.dtype(dict( formats=[np.uint8, np.uint16, np.uint8, np.uint16, np.uint32, np.uint32, np.uint8 ], offsets=[0, 2, 4, 6, 8, 12, 16], names=['a', 'b', 'c', 'd', 'e', 'f', 'g'], itemsize=18)) self.check(PackedStructure, expected)
Example #18
Source File: parallel_map.py From dataflow with Apache License 2.0 | 5 votes |
def _create_shared_arr(self): TYPE = { np.float32: ctypes.c_float, np.float64: ctypes.c_double, np.uint8: ctypes.c_uint8, np.int8: ctypes.c_int8, np.int32: ctypes.c_int32, } ctype = TYPE[self.output_dtype] arr = mp.RawArray(ctype, int(np.prod(self.output_shape))) return arr
Example #19
Source File: test_dtype.py From GraphicDesignPatternByPython with MIT License | 5 votes |
def test_padded_structure(self): class PaddedStruct(ctypes.Structure): _fields_ = [ ('a', ctypes.c_uint8), ('b', ctypes.c_uint16) ] expected = np.dtype([ ('a', np.uint8), ('b', np.uint16) ], align=True) self.check(PaddedStruct, expected)
Example #20
Source File: test_dtype.py From Mastering-Elasticsearch-7.0 with MIT License | 5 votes |
def test_simple_endian_types(self): self.check(ctypes.c_uint16.__ctype_le__, np.dtype('<u2')) self.check(ctypes.c_uint16.__ctype_be__, np.dtype('>u2')) self.check(ctypes.c_uint8.__ctype_le__, np.dtype('u1')) self.check(ctypes.c_uint8.__ctype_be__, np.dtype('u1'))
Example #21
Source File: jlink.py From pylink with Apache License 2.0 | 5 votes |
def swo_read(self, offset, num_bytes, remove=False): """Reads data from the SWO buffer. The data read is not automatically removed from the SWO buffer after reading unless ``remove`` is ``True``. Otherwise the callee must explicitly remove the data by calling ``.swo_flush()``. Args: self (JLink): the ``JLink`` instance offset (int): offset of first byte to be retrieved num_bytes (int): number of bytes to read remove (bool): if data should be removed from buffer after read Returns: A list of bytes read from the SWO buffer. """ buf_size = ctypes.c_uint32(num_bytes) buf = (ctypes.c_uint8 * num_bytes)(0) self._dll.JLINKARM_SWO_Read(buf, offset, ctypes.byref(buf_size)) # After the call, ``buf_size`` has been modified to be the actual # number of bytes that was read. buf_size = buf_size.value if remove: self.swo_flush(buf_size) return list(buf)[:buf_size]
Example #22
Source File: test_dtype.py From Mastering-Elasticsearch-7.0 with MIT License | 5 votes |
def test_big_endian_structure(self): class PaddedStruct(ctypes.BigEndianStructure): _fields_ = [ ('a', ctypes.c_uint8), ('b', ctypes.c_uint16) ] expected = np.dtype([ ('a', '>B'), ('b', '>H') ], align=True) self.check(PaddedStruct, expected)
Example #23
Source File: debuginfo.py From debin with Apache License 2.0 | 5 votes |
def get_array_upper_bound(self, die): for child in die.iter_children(): if child.tag == 'DW_TAG_subrange_type': upper_bound_attr = child.attributes.get('DW_AT_upper_bound', None) if upper_bound_attr is None: return None else: if upper_bound_attr.form in ('DW_FORM_data1', 'DW_FORM_data2', 'DW_FORM_data4', 'DW_FORM_data8'): return upper_bound_attr.value elif upper_bound_attr.form == 'DW_FORM_exprloc': loc = upper_bound_attr.value if loc[0] == ENUM_DW_FORM_exprloc['DW_OP_const1u']: return ctypes.c_uint8(loc[1]).value elif loc[0] == ENUM_DW_FORM_exprloc['DW_OP_const1s']: return ctypes.c_int8(loc[1]).value elif loc[0] == ENUM_DW_FORM_exprloc['DW_OP_const2u']: return ctypes.c_uint16(utils.decode_kbytes(loc[1:], 2)).value elif loc[0] == ENUM_DW_FORM_exprloc['DW_OP_const2s']: return ctypes.c_int16(utils.decode_kbytes(loc[1:], 2)).value elif loc[0] == ENUM_DW_FORM_exprloc['DW_OP_const4u']: return ctypes.c_uint32(utils.decode_kbytes(loc[1:], 2)).value elif loc[0] == ENUM_DW_FORM_exprloc['DW_OP_const4s']: return ctypes.c_int32(utils.decode_kbytes(loc[1:], 2)).value elif loc[0] == ENUM_DW_FORM_exprloc['DW_OP_const8u']: return ctypes.c_uint64(utils.decode_kbytes(loc[1:], 2)).value elif loc[0] == ENUM_DW_FORM_exprloc['DW_OP_const8s']: return ctypes.c_int64(utils.decode_kbytes(loc[1:], 2)).value elif loc[0] == ENUM_DW_FORM_exprloc['DW_OP_constu']: return utils.decode_uleb128(loc[1:]) elif loc[0] == ENUM_DW_FORM_exprloc['DW_OP_consts']: return utils.decode_sleb128(loc[1:]) else: return None else: return None
Example #24
Source File: test_dtype.py From GraphicDesignPatternByPython with MIT License | 5 votes |
def test_packed_structure(self): class PackedStructure(ctypes.Structure): _pack_ = 1 _fields_ = [ ('a', ctypes.c_uint8), ('b', ctypes.c_uint16) ] expected = np.dtype([ ('a', np.uint8), ('b', np.uint16) ]) self.check(PackedStructure, expected)
Example #25
Source File: jlink.py From pylink with Apache License 2.0 | 5 votes |
def register_write_multiple(self, register_indices, values): """Writes to multiple CPU registers. Writes the values to the given registers in order. There must be a one-to-one correspondence between the values and the registers specified. Args: self (JLink): the ``JLink`` instance register_indices (list): list of registers to write to values (list): list of values to write to the registers Returns: ``None`` Raises: ValueError: if ``len(register_indices) != len(values)`` JLinkException: if a register could not be written to or on error """ # TODO: rename 'register_indices' to 'registers' register_indices = register_indices[:] if len(register_indices) != len(values): raise ValueError('Must be an equal number of registers and values') num_regs = len(register_indices) for idx, indice in enumerate(register_indices): if isinstance(indice, six.string_types): register_indices[idx] = self._get_register_index_from_name(indice) buf = (ctypes.c_uint32 * num_regs)(*register_indices) data = (ctypes.c_uint32 * num_regs)(*values) # TODO: For some reason, these statuses are wonky, not sure why, might # be bad documentation, but they cannot be trusted at all. statuses = (ctypes.c_uint8 * num_regs)(0) res = self._dll.JLINKARM_WriteRegs(buf, data, statuses, num_regs) if res != 0: raise errors.JLinkException(res) return None
Example #26
Source File: test_dtype.py From GraphicDesignPatternByPython with MIT License | 5 votes |
def test_little_endian_structure(self): class PaddedStruct(ctypes.LittleEndianStructure): _fields_ = [ ('a', ctypes.c_uint8), ('b', ctypes.c_uint16) ] expected = np.dtype([ ('a', '<B'), ('b', '<H') ], align=True) self.check(PaddedStruct, expected)
Example #27
Source File: jlink.py From pylink with Apache License 2.0 | 5 votes |
def register_read_multiple(self, register_indices): """Retrieves the values from the registers specified. Args: self (JLink): the ``JLink`` instance register_indices (list): list of registers to read Returns: A list of values corresponding one-to-one for each of the given register indices. The returned list of values are the values in order of which the indices were specified. Raises: JLinkException: if a given register is invalid or an error occurs. """ # TODO: rename 'register_indices' to 'registers' register_indices = register_indices[:] num_regs = len(register_indices) for idx, indice in enumerate(register_indices): if isinstance(indice, six.string_types): register_indices[idx] = self._get_register_index_from_name(indice) buf = (ctypes.c_uint32 * num_regs)(*register_indices) data = (ctypes.c_uint32 * num_regs)(0) # TODO: For some reason, these statuses are wonky, not sure why, might # be bad documentation, but they cannot be trusted at all. statuses = (ctypes.c_uint8 * num_regs)(0) res = self._dll.JLINKARM_ReadRegs(buf, data, statuses, num_regs) if res < 0: raise errors.JLinkException(res) return list(data)
Example #28
Source File: test_dtype.py From GraphicDesignPatternByPython with MIT License | 5 votes |
def test_big_endian_structure(self): class PaddedStruct(ctypes.BigEndianStructure): _fields_ = [ ('a', ctypes.c_uint8), ('b', ctypes.c_uint16) ] expected = np.dtype([ ('a', '>B'), ('b', '>H') ], align=True) self.check(PaddedStruct, expected)
Example #29
Source File: jlink.py From pylink with Apache License 2.0 | 5 votes |
def swd_read8(self, offset): """Gets a unit of ``8`` bits from the input buffer. Args: self (JLink): the ``JLink`` instance offset (int): the offset (in bits) from which to start reading Returns: The integer read from the input buffer. """ value = self._dll.JLINK_SWD_GetU8(offset) return ctypes.c_uint8(value).value
Example #30
Source File: jlink.py From pylink with Apache License 2.0 | 5 votes |
def code_memory_read(self, addr, num_bytes): """Reads bytes from code memory. Note: This is similar to calling ``memory_read`` or ``memory_read8``, except that this uses a cache and reads ahead. This should be used in instances where you want to read a small amount of bytes at a time, and expect to always read ahead. Args: self (JLink): the ``JLink`` instance addr (int): starting address from which to read num_bytes (int): number of bytes to read Returns: A list of bytes read from the target. Raises: JLinkException: if memory could not be read. """ buf_size = num_bytes buf = (ctypes.c_uint8 * buf_size)() res = self._dll.JLINKARM_ReadCodeMem(addr, buf_size, buf) if res < 0: raise errors.JLinkException(res) return list(buf)[:res]