我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用ctypes.cast()。
def rawaddressof(self, BTypePtr, cdata, offset=None): if isinstance(cdata, CTypesBaseStructOrUnion): ptr = ctypes.pointer(type(cdata)._to_ctypes(cdata)) elif isinstance(cdata, CTypesGenericPtr): if offset is None or not issubclass(type(cdata)._BItem, CTypesBaseStructOrUnion): raise TypeError("unexpected cdata type") ptr = type(cdata)._to_ctypes(cdata) elif isinstance(cdata, CTypesGenericArray): ptr = type(cdata)._to_ctypes(cdata) else: raise TypeError("expected a <cdata 'struct-or-union'>") if offset: ptr = ctypes.cast( ctypes.c_void_p( ctypes.cast(ptr, ctypes.c_void_p).value + offset), type(ptr)) return BTypePtr._from_ctypes(ptr)
def to_rain(cls, val): if val is None: return cls.new(typi.null, 0, 0, cls.null) elif val is False: return cls.new(typi.bool, 0, 0, cls.null) elif val is True: return cls.new(typi.bool, 0, 1, cls.null) elif isinstance(val, int): return cls.new(typi.int, 0, val, cls.null) elif isinstance(val, float): raw = struct.pack('d', val) intrep = struct.unpack('Q', raw)[0] return cls.new(typi.float, 0, intrep, cls.null) elif isinstance(val, str): str_p = ct.create_string_buffer(val.encode('utf-8')) cls._saves_.append(str_p) return cls.new(typi.str, len(val), ct.cast(str_p, ct.c_void_p).value, cls.null) raise Exception("Can't convert value {!r} to Rain".format(val))
def simxCopyPasteObjects(clientID, objectHandles, operationMode): ''' Please have a look at the function description/documentation in the V-REP user manual ''' c_objectHandles = (ct.c_int*len(objectHandles))(*objectHandles) c_objectHandles = ct.cast(c_objectHandles,ct.POINTER(ct.c_int)) # IronPython needs this newObjectCount = ct.c_int() newObjectHandles = ct.POINTER(ct.c_int)() ret = c_CopyPasteObjects(clientID, c_objectHandles, len(objectHandles), ct.byref(newObjectHandles), ct.byref(newObjectCount), operationMode) newobj = [] if ret == 0: for i in range(newObjectCount.value): newobj.append(newObjectHandles[i]) return ret, newobj
def simxSetStringSignal(clientID, signalName, signalValue, operationMode): ''' Please have a look at the function description/documentation in the V-REP user manual ''' sigV=signalValue if sys.version_info[0] == 3: if type(signalName) is str: signalName=signalName.encode('utf-8') if type(signalValue) is bytearray: sigV = (ct.c_ubyte*len(signalValue))(*signalValue) if type(signalValue) is str: signalValue=signalValue.encode('utf-8') sigV = (ct.c_ubyte*len(signalValue))(*signalValue) else: if type(signalValue) is bytearray: sigV = (ct.c_ubyte*len(signalValue))(*signalValue) if type(signalValue) is str: signalValue=bytearray(signalValue) sigV = (ct.c_ubyte*len(signalValue))(*signalValue) sigV=ct.cast(sigV,ct.POINTER(ct.c_ubyte)) # IronPython needs this return c_SetStringSignal(clientID, signalName, sigV, len(signalValue), operationMode)
def simxAppendStringSignal(clientID, signalName, signalValue, operationMode): ''' Please have a look at the function description/documentation in the V-REP user manual ''' sigV=signalValue if sys.version_info[0] == 3: if type(signalName) is str: signalName=signalName.encode('utf-8') if type(signalValue) is bytearray: sigV = (ct.c_ubyte*len(signalValue))(*signalValue) if type(signalValue) is str: signalValue=signalValue.encode('utf-8') sigV = (ct.c_ubyte*len(signalValue))(*signalValue) else: if type(signalValue) is bytearray: sigV = (ct.c_ubyte*len(signalValue))(*signalValue) if type(signalValue) is str: signalValue=bytearray(signalValue) sigV = (ct.c_ubyte*len(signalValue))(*signalValue) sigV=ct.cast(sigV,ct.POINTER(ct.c_ubyte)) # IronPython needs this return c_AppendStringSignal(clientID, signalName, sigV, len(signalValue), operationMode)
def simxWriteStringStream(clientID, signalName, signalValue, operationMode): ''' Please have a look at the function description/documentation in the V-REP user manual ''' sigV=signalValue if sys.version_info[0] == 3: if type(signalName) is str: signalName=signalName.encode('utf-8') if type(signalValue) is bytearray: sigV = (ct.c_ubyte*len(signalValue))(*signalValue) if type(signalValue) is str: signalValue=signalValue.encode('utf-8') sigV = (ct.c_ubyte*len(signalValue))(*signalValue) else: if type(signalValue) is bytearray: sigV = (ct.c_ubyte*len(signalValue))(*signalValue) if type(signalValue) is str: signalValue=bytearray(signalValue) sigV = (ct.c_ubyte*len(signalValue))(*signalValue) sigV=ct.cast(sigV,ct.POINTER(ct.c_ubyte)) # IronPython needs this return c_WriteStringStream(clientID, signalName, sigV, len(signalValue), operationMode)
def test_arraystruct(self): import pygame.tests.test_utils.arrinter as ai import ctypes as ct c_byte_p = ct.POINTER(ct.c_byte) c = pygame.Color(5, 7, 13, 23) flags = (ai.PAI_CONTIGUOUS | ai.PAI_FORTRAN | ai.PAI_ALIGNED | ai.PAI_NOTSWAPPED) for i in range(1, 5): c.set_length(i) inter = ai.ArrayInterface(c) self.assertEqual(inter.two, 2) self.assertEqual(inter.nd, 1) self.assertEqual(inter.typekind, 'u') self.assertEqual(inter.itemsize, 1) self.assertEqual(inter.flags, flags) self.assertEqual(inter.shape[0], i) self.assertEqual(inter.strides[0], 1) data = ct.cast(inter.data, c_byte_p) for j in range(i): self.assertEqual(data[j], c[j])
def query_memory(self, addr): """Query the memory informations about page at ``addr`` :rtype: :class:`~windows.generated_def.MEMORY_BASIC_INFORMATION` """ if windows.current_process.bitness == 32 and self.bitness == 64: res = MEMORY_BASIC_INFORMATION64() try: v = windows.syswow64.NtQueryVirtualMemory_32_to_64(ProcessHandle=self.handle, BaseAddress=addr, MemoryInformationClass=MemoryBasicInformation, MemoryInformation=res) except NtStatusException as e: if e.code & 0xffffffff == 0XC000000D: raise winproxy.Kernel32Error("NtQueryVirtualMemory_32_to_64") raise return res info_type = {32 : MEMORY_BASIC_INFORMATION32, 64 : MEMORY_BASIC_INFORMATION64} res = info_type[windows.current_process.bitness]() ptr = ctypes.cast(byref(res), POINTER(MEMORY_BASIC_INFORMATION)) winproxy.VirtualQueryEx(self.handle, addr, ptr, sizeof(res)) return res
def peb_syswow_addr(self): if not self.is_wow_64: raise ValueError("Not a syswow process") if windows.current_process.bitness == 64: information_type = 0 x = PROCESS_BASIC_INFORMATION() winproxy.NtQueryInformationProcess(self.handle, information_type, x) peb_addr = ctypes.cast(x.PebBaseAddress, PVOID).value return peb_addr else: #current is 32bits x = windows.remotectypes.transform_type_to_remote64bits(PROCESS_BASIC_INFORMATION) # Fuck-it <3 data = (ctypes.c_char * ctypes.sizeof(x))() windows.syswow64.NtQueryInformationProcess_32_to_64(self.handle, ProcessInformation=data, ProcessInformationLength=ctypes.sizeof(x)) peb_offset = x.PebBaseAddress.offset peb_addr = struct.unpack("<Q", data[x.PebBaseAddress.offset: x.PebBaseAddress.offset+8])[0] return peb_addr # Not a fixedpropety to prevent ref-cycle and uncollectable WinProcess # Try with a weakref ?
def modules(self): """The loaded modules present in the PEB :type: [:class:`LoadedModule`] -- List of loaded modules """ res = [] list_entry_ptr = ctypes.cast(self.Ldr.contents.InMemoryOrderModuleList.Flink, LIST_ENTRY_PTR) current_dll = list_entry_ptr.TO_LDR_ENTRY() while current_dll.DllBase: res.append(current_dll) list_entry_ptr = ctypes.cast(current_dll.InMemoryOrderLinks.Flink, LIST_ENTRY_PTR) current_dll = list_entry_ptr.TO_LDR_ENTRY() return [LoadedModule.from_address(addressof(LDR)) for LDR in res] # Memory stuff
def query_link(linkpath): utf16_len = len(linkpath) * 2 obj_attr = OBJECT_ATTRIBUTES() obj_attr.Length = ctypes.sizeof(obj_attr) obj_attr.RootDirectory = 0 obj_attr.ObjectName = pointer(LSA_UNICODE_STRING(utf16_len, utf16_len, linkpath)) obj_attr.Attributes = OBJ_CASE_INSENSITIVE obj_attr.SecurityDescriptor = 0 obj_attr.SecurityQualityOfService = 0 res = HANDLE() x = winproxy.NtOpenSymbolicLinkObject(res, DIRECTORY_QUERY | READ_CONTROL , obj_attr) v = LSA_UNICODE_STRING(0x1000, 0x1000, ctypes.cast(ctypes.c_buffer(0x1000), ctypes.c_wchar_p)) s = ULONG() winproxy.NtQuerySymbolicLinkObject(res, v, s) return v.Buffer
def get_current_window(dpy): """ Returns active window or root window if there is no active. """ # Try using WM-provided info first trash, prop = get_window_prop(dpy, get_default_root_window(dpy), "_NET_ACTIVE_WINDOW") if prop is not None: rv = cast(prop, POINTER(Atom)).contents.value free(prop) return rv # Fall-back to something what probably can't work anyway win, revert_to = XID(), c_int() get_input_focus(dpy, byref(win), byref(revert_to)) if win == 0: return get_default_root_window(dpy) return win
def get(self): arg = DrmModeObjGetPropertiesC() arg.obj_id = self.obj_id arg.obj_type = self.obj_type fcntl.ioctl(self._drm.fd, DRM_IOCTL_MODE_OBJ_GETPROPERTIES, arg) prop_ids = (ctypes.c_uint32*arg.count_props)() arg.props_ptr = ctypes.cast(ctypes.pointer(prop_ids), ctypes.c_void_p).value prop_values = (ctypes.c_uint64*arg.count_props)() arg.prop_values_ptr = ctypes.cast(ctypes.pointer(prop_values), ctypes.c_void_p).value fcntl.ioctl(self._drm.fd, DRM_IOCTL_MODE_OBJ_GETPROPERTIES, arg) self._arg = arg vals = [v for i, v in zip(prop_ids, prop_values) if i == self.id] return vals[0]
def set(self, fb, x, y, mode, *conns): arg = DrmModeCrtcC() arg.crtc_id = self.id arg.fb_id = fb.id arg.x = x arg.y = y arg.mode_valid = 1 arg.mode = mode._arg connector_ids = (ctypes.c_uint32 * len(conns))(*[conn.id for conn in conns]) arg.set_connectors_ptr = ctypes.cast(ctypes.pointer(connector_ids), ctypes.c_void_p).value arg.count_connectors = len(conns) fcntl.ioctl(self._drm.fd, DRM_IOCTL_MODE_SETCRTC, arg) self.fetch()
def listDevices(flags=0): """Return a list of serial numbers(default), descriptions or locations (Windows only) of the connected FTDI devices depending on value of flags""" n = _ft.DWORD() call_ft(_ft.FT_ListDevices, c.byref(n), None, _ft.DWORD(LIST_NUMBER_ONLY)) devcount = n.value if devcount: # since ctypes has no pointer arithmetic. bd = [c.c_buffer(MAX_DESCRIPTION_SIZE) for i in range(devcount)] +\ [None] # array of pointers to those strings, initially all NULL ba = (c.c_char_p *(devcount + 1))() for i in range(devcount): ba[i] = c.cast(bd[i], c.c_char_p) call_ft(_ft.FT_ListDevices, ba, c.byref(n), _ft.DWORD(LIST_ALL|flags)) return [res for res in ba[:devcount]] else: return None
def eeRead(self): """Get the program information from the EEPROM""" ## if self.devInfo['type'] == 4: ## version = 1 ## elif self.devInfo['type'] == 5: ## version = 2 ## else: ## version = 0 progdata = _ft.ft_program_data( Signature1=0, Signature2=0xffffffff, Version=2, Manufacturer = c.cast(c.c_buffer(256), c.c_char_p), ManufacturerId = c.cast(c.c_buffer(256), c.c_char_p), Description = c.cast(c.c_buffer(256), c.c_char_p), SerialNumber = c.cast(c.c_buffer(256), c.c_char_p)) call_ft(_ft.FT_EE_Read, self.handle, c.byref(progdata)) return progdata
def wrap(self, gammaramp): ''' Wraps a nested python sequence. ''' red, green, blue = gammaramp size = min(len(red), len(green), len(blue)) array_type = ctypes.c_ushort*size self.size = ctypes.c_uint(size) self.red_array = array_type() self.green_array = array_type() self.blue_array = array_type() for i in range(self.size): self.red_array[i] = int(red[i]*65535) self.green_array[i] = int(green[i]*65535) self.blue_array[i] = int(blue[i]*65535) pointer_type = ctypes.POINTER(ctypes.c_ushort) self.red = ctypes.cast(self.red_array, pointer_type) self.green = ctypes.cast(self.green_array, pointer_type) self.blue = ctypes.cast(self.blue_array, pointer_type)
def set_window_pos_callback(window, cbfun): ''' Sets the position callback for the specified window. Wrapper for: GLFWwindowposfun glfwSetWindowPosCallback(GLFWwindow* window, GLFWwindowposfun cbfun); ''' window_addr = ctypes.cast(ctypes.pointer(window), ctypes.POINTER(ctypes.c_long)).contents.value if window_addr in _window_pos_callback_repository: previous_callback = _window_pos_callback_repository[window_addr] else: previous_callback = None if cbfun is None: cbfun = 0 c_cbfun = _GLFWwindowposfun(cbfun) _window_pos_callback_repository[window_addr] = (cbfun, c_cbfun) cbfun = c_cbfun _glfw.glfwSetWindowPosCallback(window, cbfun) if previous_callback is not None and previous_callback[0] != 0: return previous_callback[0]
def set_window_size_callback(window, cbfun): ''' Sets the size callback for the specified window. Wrapper for: GLFWwindowsizefun glfwSetWindowSizeCallback(GLFWwindow* window, GLFWwindowsizefun cbfun); ''' window_addr = ctypes.cast(ctypes.pointer(window), ctypes.POINTER(ctypes.c_long)).contents.value if window_addr in _window_size_callback_repository: previous_callback = _window_size_callback_repository[window_addr] else: previous_callback = None if cbfun is None: cbfun = 0 c_cbfun = _GLFWwindowsizefun(cbfun) _window_size_callback_repository[window_addr] = (cbfun, c_cbfun) cbfun = c_cbfun _glfw.glfwSetWindowSizeCallback(window, cbfun) if previous_callback is not None and previous_callback[0] != 0: return previous_callback[0]
def set_window_close_callback(window, cbfun): ''' Sets the close callback for the specified window. Wrapper for: GLFWwindowclosefun glfwSetWindowCloseCallback(GLFWwindow* window, GLFWwindowclosefun cbfun); ''' window_addr = ctypes.cast(ctypes.pointer(window), ctypes.POINTER(ctypes.c_long)).contents.value if window_addr in _window_close_callback_repository: previous_callback = _window_close_callback_repository[window_addr] else: previous_callback = None if cbfun is None: cbfun = 0 c_cbfun = _GLFWwindowclosefun(cbfun) _window_close_callback_repository[window_addr] = (cbfun, c_cbfun) cbfun = c_cbfun _glfw.glfwSetWindowCloseCallback(window, cbfun) if previous_callback is not None and previous_callback[0] != 0: return previous_callback[0]
def set_window_focus_callback(window, cbfun): ''' Sets the focus callback for the specified window. Wrapper for: GLFWwindowfocusfun glfwSetWindowFocusCallback(GLFWwindow* window, GLFWwindowfocusfun cbfun); ''' window_addr = ctypes.cast(ctypes.pointer(window), ctypes.POINTER(ctypes.c_long)).contents.value if window_addr in _window_focus_callback_repository: previous_callback = _window_focus_callback_repository[window_addr] else: previous_callback = None if cbfun is None: cbfun = 0 c_cbfun = _GLFWwindowfocusfun(cbfun) _window_focus_callback_repository[window_addr] = (cbfun, c_cbfun) cbfun = c_cbfun _glfw.glfwSetWindowFocusCallback(window, cbfun) if previous_callback is not None and previous_callback[0] != 0: return previous_callback[0]
def set_window_iconify_callback(window, cbfun): ''' Sets the iconify callback for the specified window. Wrapper for: GLFWwindowiconifyfun glfwSetWindowIconifyCallback(GLFWwindow* window, GLFWwindowiconifyfun cbfun); ''' window_addr = ctypes.cast(ctypes.pointer(window), ctypes.POINTER(ctypes.c_long)).contents.value if window_addr in _window_iconify_callback_repository: previous_callback = _window_iconify_callback_repository[window_addr] else: previous_callback = None if cbfun is None: cbfun = 0 c_cbfun = _GLFWwindowiconifyfun(cbfun) _window_iconify_callback_repository[window_addr] = (cbfun, c_cbfun) cbfun = c_cbfun _glfw.glfwSetWindowIconifyCallback(window, cbfun) if previous_callback is not None and previous_callback[0] != 0: return previous_callback[0]
def set_framebuffer_size_callback(window, cbfun): ''' Sets the framebuffer resize callback for the specified window. Wrapper for: GLFWframebuffersizefun glfwSetFramebufferSizeCallback(GLFWwindow* window, GLFWframebuffersizefun cbfun); ''' window_addr = ctypes.cast(ctypes.pointer(window), ctypes.POINTER(ctypes.c_long)).contents.value if window_addr in _framebuffer_size_callback_repository: previous_callback = _framebuffer_size_callback_repository[window_addr] else: previous_callback = None if cbfun is None: cbfun = 0 c_cbfun = _GLFWframebuffersizefun(cbfun) _framebuffer_size_callback_repository[window_addr] = (cbfun, c_cbfun) cbfun = c_cbfun _glfw.glfwSetFramebufferSizeCallback(window, cbfun) if previous_callback is not None and previous_callback[0] != 0: return previous_callback[0]
def set_key_callback(window, cbfun): ''' Sets the key callback. Wrapper for: GLFWkeyfun glfwSetKeyCallback(GLFWwindow* window, GLFWkeyfun cbfun); ''' window_addr = ctypes.cast(ctypes.pointer(window), ctypes.POINTER(ctypes.c_long)).contents.value if window_addr in _key_callback_repository: previous_callback = _key_callback_repository[window_addr] else: previous_callback = None if cbfun is None: cbfun = 0 c_cbfun = _GLFWkeyfun(cbfun) _key_callback_repository[window_addr] = (cbfun, c_cbfun) cbfun = c_cbfun _glfw.glfwSetKeyCallback(window, cbfun) if previous_callback is not None and previous_callback[0] != 0: return previous_callback[0]
def set_char_callback(window, cbfun): ''' Sets the Unicode character callback. Wrapper for: GLFWcharfun glfwSetCharCallback(GLFWwindow* window, GLFWcharfun cbfun); ''' window_addr = ctypes.cast(ctypes.pointer(window), ctypes.POINTER(ctypes.c_long)).contents.value if window_addr in _char_callback_repository: previous_callback = _char_callback_repository[window_addr] else: previous_callback = None if cbfun is None: cbfun = 0 c_cbfun = _GLFWcharfun(cbfun) _char_callback_repository[window_addr] = (cbfun, c_cbfun) cbfun = c_cbfun _glfw.glfwSetCharCallback(window, cbfun) if previous_callback is not None and previous_callback[0] != 0: return previous_callback[0]
def set_cursor_pos_callback(window, cbfun): ''' Sets the cursor position callback. Wrapper for: GLFWcursorposfun glfwSetCursorPosCallback(GLFWwindow* window, GLFWcursorposfun cbfun); ''' window_addr = ctypes.cast(ctypes.pointer(window), ctypes.POINTER(ctypes.c_long)).contents.value if window_addr in _cursor_pos_callback_repository: previous_callback = _cursor_pos_callback_repository[window_addr] else: previous_callback = None if cbfun is None: cbfun = 0 c_cbfun = _GLFWcursorposfun(cbfun) _cursor_pos_callback_repository[window_addr] = (cbfun, c_cbfun) cbfun = c_cbfun _glfw.glfwSetCursorPosCallback(window, cbfun) if previous_callback is not None and previous_callback[0] != 0: return previous_callback[0]
def set_cursor_enter_callback(window, cbfun): ''' Sets the cursor enter/exit callback. Wrapper for: GLFWcursorenterfun glfwSetCursorEnterCallback(GLFWwindow* window, GLFWcursorenterfun cbfun); ''' window_addr = ctypes.cast(ctypes.pointer(window), ctypes.POINTER(ctypes.c_long)).contents.value if window_addr in _cursor_enter_callback_repository: previous_callback = _cursor_enter_callback_repository[window_addr] else: previous_callback = None if cbfun is None: cbfun = 0 c_cbfun = _GLFWcursorenterfun(cbfun) _cursor_enter_callback_repository[window_addr] = (cbfun, c_cbfun) cbfun = c_cbfun _glfw.glfwSetCursorEnterCallback(window, cbfun) if previous_callback is not None and previous_callback[0] != 0: return previous_callback[0]
def set_scroll_callback(window, cbfun): ''' Sets the scroll callback. Wrapper for: GLFWscrollfun glfwSetScrollCallback(GLFWwindow* window, GLFWscrollfun cbfun); ''' window_addr = ctypes.cast(ctypes.pointer(window), ctypes.POINTER(ctypes.c_long)).contents.value if window_addr in _scroll_callback_repository: previous_callback = _scroll_callback_repository[window_addr] else: previous_callback = None if cbfun is None: cbfun = 0 c_cbfun = _GLFWscrollfun(cbfun) _scroll_callback_repository[window_addr] = (cbfun, c_cbfun) cbfun = c_cbfun _glfw.glfwSetScrollCallback(window, cbfun) if previous_callback is not None and previous_callback[0] != 0: return previous_callback[0]
def render(self): if not self.data: return self.gui_lock.acquire() rect = self.get_rect() arr = (ctypes.c_double*3)(0, 0, 0) mjlib.mjv_makeGeoms(self.model.ptr, self.data.ptr, byref(self.objects), byref(self.vopt), mjCAT_ALL, 0, None, None, ctypes.cast(arr, ctypes.POINTER(ctypes.c_double))) mjlib.mjv_makeLights(self.model.ptr, self.data.ptr, byref(self.objects)) mjlib.mjv_setCamera(self.model.ptr, self.data.ptr, byref(self.cam)) mjlib.mjv_updateCameraPose(byref(self.cam), rect.width*1.0/rect.height) mjlib.mjr_render(0, rect, byref(self.objects), byref(self.ropt), byref(self.cam.pose), byref(self.con)) self.gui_lock.release()
def cast_2d_list_to_2d_pointer(list_value_2d, c_type=ctypes.c_double): '''Cast Python 2d-list to 2d-pointer of c_types Args: list_value_2d (List[List[:object:]]): 2d-Python list c_type (ctypes, default: ctypes.c_double): target type Returns: POINTER(POINTER(c_type)): ctypes 2d-pointer ''' inner_arr_type = c_type * len(list_value_2d[0]) outer_arr_type = inner_arr_type * len(list_value_2d) tmp_buffer = outer_arr_type() pointer_2d = ctypes.cast(tmp_buffer, ctypes.POINTER(ctypes.POINTER(c_type))) outer_size = len(list_value_2d) for i in range(outer_size): pointer_2d[i] = ctypes.cast(inner_arr_type(*list_value_2d[i]), ctypes.POINTER(c_type)) return pointer_2d
def load_name(self, offset): """ Load a timezone name from a DLL offset (integer). >>> from dateutil.tzwin import tzres >>> tzr = tzres() >>> print(tzr.load_name(112)) 'Eastern Standard Time' :param offset: A positive integer value referring to a string from the tzres dll. ..note: Offsets found in the registry are generally of the form `@tzres.dll,-114`. The offset in this case if 114, not -114. """ resource = self.p_wchar() lpBuffer = ctypes.cast(ctypes.byref(resource), wintypes.LPWSTR) nchar = self.LoadStringW(self._tzres._handle, offset, lpBuffer, 0) return resource[:nchar]
def tracks_get(self): """Get media descriptor's elementary streams description Note, you need to call L{parse}() or play the media at least once before calling this function. Not doing this will result in an empty array. The result must be freed with L{tracks_release}. @version: LibVLC 2.1.0 and later. """ mediaTrack_pp = ctypes.POINTER(MediaTrack)() n = libvlc_media_tracks_get(self, ctypes.byref(mediaTrack_pp)) info = ctypes.cast(mediaTrack_pp, ctypes.POINTER(ctypes.POINTER(MediaTrack) * n)) try: contents = info.contents except ValueError: # Media not parsed, no info. return None tracks = ( contents[i].contents for i in range(len(contents)) ) # libvlc_media_tracks_release(mediaTrack_pp, n) return tracks
def __str__(self): longest_name = max([len(k[0]) for k in self._fields_]) indent_fmt = '{{:>{}s}}: {{}}\n'.format(longest_name) indent_verbose_fmt = '{{:>{}s}}: {{}} ({{}})\n'.format(longest_name) out = '' for k in self._fields_: value = getattr(self, k[0]) if k[0] in ('chaddr', 'sname', 'file'): value = ctypes.cast(value, c_char_p).value out += indent_fmt.format(k[0], value.hex() if PY3 else value.encode('hex')) elif k[0] in ('xid'): out += indent_verbose_fmt.format(k[0], value, hex(value).rstrip('L')) elif k[0] in ('flags'): out += indent_verbose_fmt.format(k[0], value, 'broadcast' if value & 0x8000 else hex(value)) elif k[0] in ('op'): out += indent_verbose_fmt.format(k[0], value, opcodes.get(value, '?')) elif k[0] in ('htype'): out += indent_verbose_fmt.format(k[0], value, hw_types.get(value, '?')) elif k[0] in ('ciaddr', 'yiaddr', 'siaddr', 'giaddr'): out += indent_verbose_fmt.format(k[0], value, int_to_ip(value)) else: out += indent_fmt.format(k[0], value) return out.rstrip()
def gcp(self, cdata, destructor): BType = self.typeof(cdata) if destructor is None: if not (hasattr(BType, '_gcp_type') and BType._gcp_type is BType): raise TypeError("Can remove destructor only on a object " "previously returned by ffi.gc()") cdata._destructor = None return None try: gcp_type = BType._gcp_type except AttributeError: class CTypesDataGcp(BType): __slots__ = ['_orig', '_destructor'] def __del__(self): if self._destructor is not None: self._destructor(self._orig) gcp_type = BType._gcp_type = CTypesDataGcp new_cdata = self.cast(gcp_type, cdata) new_cdata._orig = cdata new_cdata._destructor = destructor return new_cdata
def _cf_string_to_unicode(value): """ Creates a Unicode string from a CFString object. Used entirely for error reporting. Yes, it annoys me quite a lot that this function is this complex. """ value_as_void_p = ctypes.cast(value, ctypes.POINTER(ctypes.c_void_p)) string = CoreFoundation.CFStringGetCStringPtr( value_as_void_p, CFConst.kCFStringEncodingUTF8 ) if string is None: buffer = ctypes.create_string_buffer(1024) result = CoreFoundation.CFStringGetCString( value_as_void_p, buffer, 1024, CFConst.kCFStringEncodingUTF8 ) if not result: raise OSError('Error copying C string from CFStringRef') string = buffer.value if string is not None: string = string.decode('utf-8') return string
def get_global(self, name, typ): '''Return a global address''' addr = self.engine.get_global_value_address(name) ptr = ct.cast(ct.c_void_p(addr), typ) return ptr # Runtime configuration #####################################################
def to_rain(self, val): if isinstance(val, (list, tuple)): table_box = T.cbox.to_rain(None) self.rain_set_table(table_box) meta_ptr = self.get_global('core.types.array.module', T.carg) self.rain_set_env(table_box, meta_ptr) for i, n in enumerate(val): self.rain_put_py(table_box, i, self.to_rain(n)) return table_box elif isinstance(val, A.node): table_box = T.cbox.to_rain(None) self.rain_set_table(table_box) ast_ptr = self.get_global('core.ast.module', T.carg) meta_ptr = self.rain_get_ptr_py(ast_ptr, val.__tag__) if not ct.cast(meta_ptr, ct.c_void_p).value: Q.abort('Unable to look up core.ast.{}'.format(val.__tag__)) self.rain_set_env(table_box, meta_ptr) slots = [self.to_rain(getattr(val, key, None)) for key in val.__slots__] for key, box in zip(val.__slots__, slots): self.rain_put_py(table_box, key, box) return table_box elif isinstance(val, K.value_token): return T.cbox.to_rain(val.value) return T.cbox.to_rain(val)