我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用ctypes.c_byte()。
def simxGetVisionSensorImage(clientID, sensorHandle, options, operationMode): ''' Please have a look at the function description/documentation in the V-REP user manual ''' resolution = (ct.c_int*2)() c_image = ct.POINTER(ct.c_byte)() bytesPerPixel = 3 if (options and 1) != 0: bytesPerPixel = 1 ret = c_GetVisionSensorImage(clientID, sensorHandle, resolution, ct.byref(c_image), options, operationMode) reso = [] image = [] if (ret == 0): image = [None]*resolution[0]*resolution[1]*bytesPerPixel for i in range(resolution[0] * resolution[1] * bytesPerPixel): image[i] = c_image[i] for i in range(2): reso.append(resolution[i]) return ret, reso, image
def win32_version(): import ctypes class OSVERSIONINFOEXW(ctypes.Structure): _fields_ = [('dwOSVersionInfoSize', ctypes.c_ulong), ('dwMajorVersion', ctypes.c_ulong), ('dwMinorVersion', ctypes.c_ulong), ('dwBuildNumber', ctypes.c_ulong), ('dwPlatformId', ctypes.c_ulong), ('szCSDVersion', ctypes.c_wchar*128), ('wServicePackMajor', ctypes.c_ushort), ('wServicePackMinor', ctypes.c_ushort), ('wSuiteMask', ctypes.c_ushort), ('wProductType', ctypes.c_byte), ('wReserved', ctypes.c_byte)] """ Get's the OS major and minor versions. Returns a tuple of (OS_MAJOR, OS_MINOR). """ os_version = OSVERSIONINFOEXW() os_version.dwOSVersionInfoSize = ctypes.sizeof(os_version) retcode = ctypes.windll.Ntdll.RtlGetVersion(ctypes.byref(os_version)) if retcode != 0: raise Exception("Failed to get OS version") return os_version.dwMajorVersion
def GetBatteryProfile(self): ret = self.interface.ReadData(self.BATTERY_PROFILE_CMD, 14) if ret['error'] != 'NO_ERROR': return ret else: d = ret['data'] if all(v == 0 for v in d): return {'data':'INVALID', 'error':'NO_ERROR'} profile = {} profile['capacity'] = (d[1] << 8) | d[0] profile['chargeCurrent'] = d[2] * 75 + 550 profile['terminationCurrent'] = d[3] * 50 + 50 profile['regulationVoltage'] = d[4] * 20 + 3500 profile['cutoffVoltage'] = d[5] * 20 profile['tempCold'] = ctypes.c_byte(d[6]).value profile['tempCool'] = ctypes.c_byte(d[7]).value profile['tempWarm'] = ctypes.c_byte(d[8]).value profile['tempHot'] = ctypes.c_byte(d[9]).value profile['ntcB'] = (d[11] << 8) | d[10] profile['ntcResistance'] = ((d[13] << 8) | d[12]) * 10 return {'data':profile, 'error':'NO_ERROR'}
def extract_plane_r36compat(frame: VideoFrame, planeno: int, *, compat: bool=False) -> Image.Image: """ Extracts the plane using the old VapourSynth API for reading a frame. Since we are doing raw memory operations using ctypes, this function has proven to be prone to SIGSEGV while developing. This code will subseqently be dropped from this codebase when VapourSynth r36 is officially dropped with the official release of R39. :param frame: The frame :param planeno: The plane number :param compat: Are we dealing with a compat format. :return: The extracted image. """ width, height = calculate_size(frame, planeno) stride = frame.get_stride(planeno) s_plane = height * stride buf = (ctypes.c_byte*s_plane).from_address(frame.get_read_ptr(planeno).value) if not compat: return Image.frombuffer('L', (width, height), buf, "raw", "L", stride, -1) else: return Image.frombuffer('RGB', (width, height), buf, "raw", "BGRX", stride, -1)
def simxSetVisionSensorImage(clientID, sensorHandle, image, options, operationMode): ''' Please have a look at the function description/documentation in the V-REP user manual ''' size = len(image) image_bytes = (ct.c_byte*size)(*image) return c_SetVisionSensorImage(clientID, sensorHandle, image_bytes, size, options, operationMode)
def __init__(self, *, slot_bytes, slot_count): """Initializer. Args: slot_bytes: How big each buffer in the array should be. slot_count: How many buffers should be in the array. """ self.slot_bytes = slot_bytes self.slot_count = slot_count self.length_bytes = 4 slot_type = ctypes.c_byte * (slot_bytes + self.length_bytes) self.array = multiprocessing.RawArray(slot_type, slot_count)
def write_to_buffer(buffer, data, offset=0): if isinstance(buffer, ctypes.POINTER(ctypes.c_byte)): ctypes.memmove(buffer, data, len(data)) return if offset == 0: buffer.value = data else: buffer.value = buffer.raw[0:offset] + data
def byte_array(byte_string): return (ctypes.c_byte * len(byte_string))(*bytes_to_list(byte_string))
def ref(value, offset=0): return ctypes.cast(ctypes.addressof(value) + offset, ctypes.POINTER(ctypes.c_byte))
def native(type_, value): if isinstance(value, type_): return value if sys.version_info < (3,) and type_ == int and isinstance(value, int_types): return value if isinstance(value, ctypes.Array) and value._type_ == ctypes.c_byte: return ctypes.string_at(ctypes.addressof(value), value._length_) return type_(value.value)
def win32_version_string(): import ctypes class OSVERSIONINFOEXW(ctypes.Structure): _fields_ = [('dwOSVersionInfoSize', ctypes.c_ulong), ('dwMajorVersion', ctypes.c_ulong), ('dwMinorVersion', ctypes.c_ulong), ('dwBuildNumber', ctypes.c_ulong), ('dwPlatformId', ctypes.c_ulong), ('szCSDVersion', ctypes.c_wchar*128), ('wServicePackMajor', ctypes.c_ushort), ('wServicePackMinor', ctypes.c_ushort), ('wSuiteMask', ctypes.c_ushort), ('wProductType', ctypes.c_byte), ('wReserved', ctypes.c_byte)] """ Get's the OS major and minor versions. Returns a tuple of (OS_MAJOR, OS_MINOR). """ os_version = OSVERSIONINFOEXW() os_version.dwOSVersionInfoSize = ctypes.sizeof(os_version) retcode = ctypes.windll.Ntdll.RtlGetVersion(ctypes.byref(os_version)) if retcode != 0: raise Exception("Failed to get OS version") version_string = "Version:%d-%d; Build:%d; Platform:%d; CSD:%s; ServicePack:%d-%d; Suite:%d; ProductType:%d" % ( os_version.dwMajorVersion, os_version.dwMinorVersion, os_version.dwBuildNumber, os_version.dwPlatformId, os_version.szCSDVersion, os_version.wServicePackMajor, os_version.wServicePackMinor, os_version.wSuiteMask, os_version.wReserved ) return version_string
def read(self, whence='earliest', guarantee=True): with ReadSequence(self, which=whence, guarantee=guarantee) as cur_seq: while True: yield cur_seq cur_seq.increment() #def _data(self): # data_ptr = _get(self.lib.bfRingLockedGetData, self.obj) # #data_ptr = c_void_p() # #self._check( self.lib.bfRingLockedGetData(self.obj, pointer(data_ptr)) ) # #data_ptr = data_ptr.value # #data_ptr = self.lib.bfRingLockedGetData(self.obj) # if self.space == 'cuda': # # TODO: See if can wrap this in something like PyCUDA's GPUArray # # Ideally actual GPUArray, but it doesn't appear to support wrapping pointers # return data_ptr # span = self._total_span() # stride = self._stride() # nringlet = self._nringlet() # #print "******", span, stride, nringlet # BufferType = c_byte*(nringlet*stride) # data_buffer_ptr = cast(data_ptr, POINTER(BufferType)) # data_buffer = data_buffer_ptr.contents # data_array = np.ndarray(shape=(nringlet, span), # strides=(stride, 1) if nringlet > 1 else None, # buffer=data_buffer, dtype=np.uint8) # return data_array #def _contiguous_span(self): # return self._get(BFsize, self.lib.bfRingLockedGetContiguousSpan, self.obj) #def _total_span(self): # return self._get(BFsize, self.lib.bfRingLockedGetTotalSpan, self.obj) #def _nringlet(self): # return self._get(BFsize, self.lib.bfRingLockedGetNRinglet, self.obj) #def _stride(self): # return self._get(BFsize, self.lib.bfRingLockedGetStride, self.obj)
def readinto(self, buf): with self.lock: assert(len(buf) % self.frame_nbyte == 0) nframe = len(buf) // self.frame_nbyte # Note: This allows buf to be a buffer/memoryview object # E.g., numpy.ndarray.data buf_view = (ctypes.c_byte * len(buf)).from_buffer(buf) # TODO: This returns PaInputOverflowed if input data were dropped # by PortAudio since the last call (equivalent to dropping # packets). _check(_lib.Pa_ReadStream(self.stream, buf_view, nframe)) return buf
def write(self, buf): with self.lock: assert(len(buf) % self.frame_nbyte == 0) nframe = len(buf) // self.frame_nbyte buf_view = (ctypes.c_byte * len(buf)).from_buffer(buf) _check(_lib.Pa_WriteStream(self.stream, buf_view, nframe)) return buf
def _address_as_buffer(address, nbyte, readonly=False): if address is None: raise ValueError("Cannot create buffer from NULL pointer") # Note: This doesn't work as a buffer when using pypy # return (ctypes.c_byte*nbyte).from_address(address) # Note: This works as a buffer in regular python and pypy # Note: int_asbuffer is undocumented; see here: # https://mail.scipy.org/pipermail/numpy-discussion/2008-January/030938.html return np.core.multiarray.int_asbuffer( address, nbyte, readonly=readonly, check=False)
def addc(self, a, b, c): if 0 == self.pc_state.P.get_D(): r = ctypes.c_short(a + b + c).value rc = ctypes.c_byte(a + b + c).value self.pc_state.P.set_N((0,1)[0x80 == (rc & 0x80)]) self.pc_state.P.set_Z((0,1)[rc == 0x0]) self.pc_state.P.set_V((0,1)[rc != r]) # Overflow r = ((a & 0xFF) + (b & 0xFF) + c) & 0xFFFF self.pc_state.P.set_C((0,1)[0x100 == (r & 0x100)]) result = (a + b + c) elif 1 == self.pc_state.P.get_D(): # Decimal Addition # FIXME need to fix flags # r = ctypes.c_short(((a >> 4) & 0xF)* 10+ ((a & 0xF) %10) + ((b>>4) & 0xF)* 10 + ((b & 0xF) %10) + c).value rc = ctypes.c_byte(a + b + c).value # ???? TODO self.pc_state.P.set_N((0,1)[r < 0]) self.pc_state.P.set_Z((0,1)[rc == 0x0]) # self.pc_state.P.V = (rc != r) ? 1:0; # Overflow self.pc_state.P.set_C((0,1)[(r > 99) or (r < 0)]) result = (((((r/10) % 10) << 4) & 0xf0) + (r%10)) return result & 0xFF
def subc(self, a, b, c): if 0 == self.pc_state.P.get_D(): r = ctypes.c_short(ctypes.c_byte(a).value - ctypes.c_byte(b).value - ctypes.c_byte(c).value).value rs = ctypes.c_byte((a - b - c) & 0xFF).value self.pc_state.P.set_N((0,1)[0x80 == (rs & 0x80)]) # Negative self.pc_state.P.set_Z((0,1)[rs == 0]) # Zero self.pc_state.P.set_V((0,1)[r != rs]) # Overflow r = a - b - c self.pc_state.P.set_C((1,0)[0x100 == (r & 0x100)]) # Carry (not borrow result = a - b - c elif 1 == self.pc_state.P.get_D(): # Decimal subtraction # FIXME need to fix flags r = ctypes.c_short(((a >> 4) & 0xF)* 10+ ((a & 0xF) %10) - (((b>>4) & 0xF)* 10 + ((b & 0xF) %10)) - c).value # rc = a + b + c self.pc_state.P.set_N((0,1)[r < 0]) self.pc_state.P.set_Z((0,1)[r == 0x0]) # Need to check/fix conditions for V # self.pc_state.P.V = (rc != r) ? 1:0; # Overflow self.pc_state.P.set_V(1) # Overflow self.pc_state.P.set_C((0,1)[(r >= 0) and (r <= 99)]) result = (((int(r/10) % 10) << 4) & 0xf0) + (r%10) return result & 0xFF
def cmp(self, a, b): r = ctypes.c_short(ctypes.c_byte(a).value - ctypes.c_byte(b).value).value rs = ctypes.c_byte(a - b).value self.pc_state.P.set_N((0,1)[0x80 == (rs & 0x80)]) # Negative self.pc_state.P.set_Z((0,1)[rs == 0]) # Zero r = (a & 0xFF) - (b & 0xFF) self.pc_state.P.set_C((1,0)[0x100 == (r & 0x100)]) # Carry (not borrow)
def _hmove_clocks(self, hm): # hm - int8 # Need to ensure 'hm' maintains negative when shifted. clock_shift = 0 # 'hm >= 0x80' is negative move. clock_shift = ctypes.c_byte(hm).value >> 4 return clock_shift
def addc(self, a, b, c): if 0 == self.pc_state.P.get_D(): r = ctypes.c_short(a + b + c).value rc = ctypes.c_byte(a + b + c).value self.pc_state.P.set_N((0,1)[0x80 == (rc & 0x80)]) self.pc_state.P.set_Z((0,1)[rc == 0x0]) self.pc_state.P.set_V((0,1)[rc != r]) # Overflow r = ((a & 0xFF) + (b & 0xFF) + c) & 0xFFFF self.pc_state.P.set_C((0,1)[0x100 == (r & 0x100)]) result = (a + b + c) elif 1 == self.pc_state.P.get_D(): # Decimal Addition # FIXME need to fix flags # r = ctypes.c_short(((a >> 4) & 0xF)* 10+ ((a & 0xF) %10) + ((b>>4) & 0xF)* 10 + ((b & 0xF) %10) + c).value rc = ctypes.c_byte(a + b + c).value # ???? TODO self.pc_state.P.set_N((0,1)[r < 0]) self.pc_state.P.set_Z((0,1)[rc == 0x0]) # self.pc_state.P.V = (rc != r) ? 1:0; # Overflow self.pc_state.P.set_C((0,1)[(r > 99) or (r < 0)]) result = ((((int(r/10) % 10) << 4) & 0xf0) + (r%10)) return result & 0xFF
def GetBool(self): value = C.c_byte() self._GetBool(self.handle, C.byref(value)) return value.value
def _create_bitmap(self, width, height): self._data = (ctypes.c_byte * (4 * width * height))() self._bitmap = ctypes.c_void_p() self._format = PixelFormat32bppARGB gdiplus.GdipCreateBitmapFromScan0(width, height, width * 4, self._format, self._data, ctypes.byref(self._bitmap)) self._graphics = ctypes.c_void_p() gdiplus.GdipGetImageGraphicsContext(self._bitmap, ctypes.byref(self._graphics)) gdiplus.GdipSetPageUnit(self._graphics, UnitPixel) self._dc = user32.GetDC(0) gdi32.SelectObject(self._dc, self.font.hfont) gdiplus.GdipSetTextRenderingHint(self._graphics, TextRenderingHintAntiAliasGridFit) self._brush = ctypes.c_void_p() gdiplus.GdipCreateSolidFill(0xffffffff, ctypes.byref(self._brush)) self._matrix = ctypes.c_void_p() gdiplus.GdipCreateMatrix(ctypes.byref(self._matrix)) self._flags = (DriverStringOptionsCmapLookup | DriverStringOptionsRealizedAdvance) self._rect = Rect(0, 0, width, height) self._bitmap_height = height
def __init__(self, size): self.size = size self.array = (ctypes.c_byte * size)() self.ptr = ctypes.cast(self.array, ctypes.c_void_p).value
def resize(self, size): array = (ctypes.c_byte * size)() ctypes.memmove(array, self.array, min(size, self.size)) self.size = size self.array = array self.ptr = ctypes.cast(self.array, ctypes.c_void_p).value
def map(self, invalidate=False): glPushClientAttrib(GL_CLIENT_VERTEX_ARRAY_BIT) glBindBuffer(self.target, self.id) if invalidate: glBufferData(self.target, self.size, None, self.usage) ptr = ctypes.cast(glMapBuffer(self.target, GL_WRITE_ONLY), ctypes.POINTER(ctypes.c_byte * self.size)).contents glPopClientAttrib() return ptr
def __init__(self, size, target, usage): super(MappableVertexBufferObject, self).__init__(size, target, usage) self.data = (ctypes.c_byte * size)() self.data_ptr = ctypes.cast(self.data, ctypes.c_void_p).value self._dirty_min = sys.maxsize self._dirty_max = 0
def resize(self, size): data = (ctypes.c_byte * size)() ctypes.memmove(data, self.data, min(size, self.size)) self.data = data self.data_ptr = ctypes.cast(self.data, ctypes.c_void_p).value self.size = size glPushClientAttrib(GL_CLIENT_VERTEX_ARRAY_BIT) glBindBuffer(self.target, self.id) glBufferData(self.target, self.size, self.data, self.usage) glPopClientAttrib() self._dirty_min = sys.maxsize self._dirty_max = 0
def hex_dump_memory(ptr, num): import ctypes s = '' n = 0 lines = [] data = list((num * ctypes.c_byte).from_address(ptr)) if len(data) == 0: return '<empty>' for i in range(0, num, 16): line = '' line += '%04x | ' % (ptr + i) n += 16 for j in range(n-16, n): if j >= len(data): break line += '%02x ' % (data[j] & 0xff) line += ' ' * (3 * 16 + 7 - len(line)) + ' | ' for j in range(n-16, n): if j >= len(data): break c = data[j] if not (data[j] < 0x20 or data[j] > 0x7e) else '.' line += '%c' % c lines.append(line) return '\n'.join(lines)