Python ctypes.wstring_at() Examples

The following are 13 code examples of ctypes.wstring_at(). 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: url_handler.py    From NVDARemote with GNU General Public License v2.0 6 votes vote down vote up
def windowProc(self, hwnd, msg, wParam, lParam):
		if msg != WM_COPYDATA:
			return
		hwnd = wParam
		struct_pointer = lParam
		message_data = ctypes.cast(struct_pointer, PCOPYDATASTRUCT)
		url = ctypes.wstring_at(message_data.contents.lpData)
		log.info("Received url: %s" % url)
		try:
			con_info = connection_info.ConnectionInfo.from_url(url)
		except connection_info.URLParsingError:
			wx.CallLater(50, gui.messageBox, parent=gui.mainFrame, caption=_("Invalid URL"),
			# Translators: Message shown when an invalid URL has been provided.
			message=_("Unable to parse url \"%s\"")%url, style=wx.OK | wx.ICON_ERROR)
			log.exception("unable to parse nvdaremote:// url %s" % url)
			raise
		log.info("Connection info: %r" % con_info)
		if callable(self.callback):
			wx.CallLater(50, self.callback, con_info) 
Example #2
Source File: vds_storage_manager.py    From cloudbase-init with Apache License 2.0 6 votes vote down vote up
def _extend_volumes(self, pack, volume_indexes):
        for unk in _enumerate(pack.QueryVolumes()):
            volume = unk.QueryInterface(vds.IVdsVolume)
            volume_prop = volume.GetProperties()
            try:
                extend_volume = True
                if volume_indexes:
                    volume_name = ctypes.wstring_at(volume_prop.pwszName)
                    volume_idx = self._get_volume_index(volume_name)
                    if volume_idx not in volume_indexes:
                        extend_volume = False

                if extend_volume:
                    self._extend_volume(pack, volume, volume_prop)
            finally:
                ole32.CoTaskMemFree(volume_prop.pwszName) 
Example #3
Source File: vds_storage_manager.py    From cloudbase-init with Apache License 2.0 6 votes vote down vote up
def _extend_volume(self, pack, volume, volume_prop):
        volume_extents = self._get_volume_extents_to_resize(pack,
                                                            volume_prop.id)
        input_disks = []

        for (volume_extent, volume_extend_size) in volume_extents:
            input_disk = vds.VDS_INPUT_DISK()
            input_disks.append(input_disk)

            input_disk.diskId = volume_extent.diskId
            input_disk.memberIdx = volume_extent.memberIdx
            input_disk.plexId = volume_extent.plexId
            input_disk.ullSize = volume_extend_size

        if input_disks:
            extend_size = sum([i.ullSize for i in input_disks])
            volume_name = ctypes.wstring_at(volume_prop.pwszName)
            LOG.info('Extending volume "%s" with %s bytes' %
                     (volume_name, extend_size))

            input_disks_ar = (vds.VDS_INPUT_DISK *
                              len(input_disks))(*input_disks)
            extend_job = volume.Extend(input_disks_ar, len(input_disks))
            extend_job.Wait() 
Example #4
Source File: pybass.py    From pybass with Apache License 2.0 5 votes vote down vote up
def get_tags(handle, tags = BASS_TAG_OGG):
	result = []
	addr = BASS_ChannelGetTags(handle, tags)
	res = b''
	while isinstance(res, (str, bytes)):
		res = ctypes.string_at(addr)
		#if sys.hexversion >= 0x03000000:
			#res = ctypes.wstring_at(addr)
		addr += len(res) + 1
		if res:
			if 32 < bass_ord(res[0]) < 256:
				result.append(res)
			else:
				res = None
	return result 
Example #5
Source File: l10n.py    From EDMarketConnector with GNU General Public License v2.0 5 votes vote down vote up
def preferredLanguages(self):

        if platform=='darwin':
            return NSLocale.preferredLanguages()

        elif platform=='win32':

            def wszarray_to_list(array):
                offset = 0
                while offset < len(array):
                    sz = ctypes.wstring_at(ctypes.addressof(array) + offset*2)
                    if sz:
                        yield sz
                        offset += len(sz)+1
                    else:
                        break

            num = ctypes.c_ulong()
            size = ctypes.c_ulong(0)
            if (GetUserPreferredUILanguages(MUI_LANGUAGE_NAME, ctypes.byref(num), None, ctypes.byref(size)) and size.value):
                buf = ctypes.create_unicode_buffer(size.value)
                if GetUserPreferredUILanguages(MUI_LANGUAGE_NAME, ctypes.byref(num), ctypes.byref(buf), ctypes.byref(size)):
                    return wszarray_to_list(buf)
            return []

        else:	# POSIX
            lang = locale.getlocale()[0]
            return lang and [lang.replace('_','-')] or []

# singletons 
Example #6
Source File: config.py    From EDMarketConnector with GNU General Public License v2.0 5 votes vote down vote up
def get(self, key):
            typ  = DWORD()
            size = DWORD()
            if RegQueryValueEx(self.hkey, key, 0, ctypes.byref(typ), None, ctypes.byref(size)) or typ.value not in [REG_SZ, REG_MULTI_SZ]:
                return None
            buf = ctypes.create_unicode_buffer(size.value / 2)
            if RegQueryValueEx(self.hkey, key, 0, ctypes.byref(typ), buf, ctypes.byref(size)):
                return None
            elif typ.value == REG_MULTI_SZ:
                return [x for x in ctypes.wstring_at(buf, len(buf)-2).split(u'\x00')]
            else:
                return unicode(buf.value) 
Example #7
Source File: registry.py    From rekall with GNU General Public License v2.0 5 votes vote down vote up
def EnumKey(key, index):
    """This calls the Windows RegEnumKeyEx function in a Unicode safe way."""
    buf = ctypes.create_unicode_buffer(257)
    length = ctypes.wintypes.DWORD(257)
    rc = RegEnumKeyEx(key.handle, index, ctypes.cast(buf, ctypes.c_wchar_p),
                      ctypes.byref(length), LPDWORD(), ctypes.c_wchar_p(),
                      LPDWORD(), ctypes.POINTER(FileTime)())
    if rc != 0:
        raise ctypes.WinError(2)

    return ctypes.wstring_at(buf, length.value).rstrip(u"\x00") 
Example #8
Source File: registry.py    From rekall with GNU General Public License v2.0 5 votes vote down vote up
def Reg2Py(data, size, data_type):
    if data_type == winreg.REG_DWORD:
        if size == 0:
            return 0
        return ctypes.cast(data, ctypes.POINTER(ctypes.c_int)).contents.value
    elif data_type == winreg.REG_SZ or data_type == winreg.REG_EXPAND_SZ:
        return ctypes.wstring_at(data, size // 2).rstrip(u"\x00")
    elif data_type == winreg.REG_MULTI_SZ:
        return ctypes.wstring_at(data, size // 2).rstrip(u"\x00").split(u"\x00")
    else:
        if size == 0:
            return None
        return ctypes.string_at(data, size) 
Example #9
Source File: _fsnative.py    From bugatsinho.github.io with GNU General Public License v3.0 5 votes vote down vote up
def _decode_surrogatepass(data, codec):
    """Like data.decode(codec, 'surrogatepass') but makes utf-16-le/be work
    on Python < 3.4 + Windows

    https://bugs.python.org/issue27971

    Raises UnicodeDecodeError, LookupError
    """

    try:
        return data.decode(codec, _surrogatepass)
    except UnicodeDecodeError:
        if not _codec_can_decode_with_surrogatepass(codec):
            if _normalize_codec(codec) == "utf-16-be":
                data = _swap_bytes(data)
                codec = "utf-16-le"
            if _normalize_codec(codec) == "utf-16-le":
                buffer_ = ctypes.create_string_buffer(data + b"\x00\x00")
                value = ctypes.wstring_at(buffer_, len(data) // 2)
                if value.encode("utf-16-le", _surrogatepass) != data:
                    raise
                return value
            else:
                raise
        else:
            raise 
Example #10
Source File: windows.py    From pyu2f with Apache License 2.0 5 votes vote down vote up
def FillDeviceAttributes(device, descriptor):
  """Fill out the attributes of the device.

  Fills the devices HidAttributes and product string
  into the descriptor.

  Args:
    device: A handle to the open device
    descriptor: The DeviceDescriptor to populate with the
      attributes.

  Returns:
    None

  Raises:
    WindowsError when unable to obtain attributes or product
      string.
  """
  attributes = HidAttributes()
  result = hid.HidD_GetAttributes(device, ctypes.byref(attributes))
  if not result:
    raise ctypes.WinError()

  buf = ctypes.create_string_buffer(1024)
  result = hid.HidD_GetProductString(device, buf, 1024)

  if not result:
    raise ctypes.WinError()

  descriptor.vendor_id = attributes.VendorID
  descriptor.product_id = attributes.ProductID
  descriptor.product_string = ctypes.wstring_at(buf) 
Example #11
Source File: process.py    From PythonForWindows with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def peb_syswow(self):
        """The 64bits PEB of a SysWow64 process

            :type: :class:`PEB`
		"""
        if not self.is_wow_64:
            raise ValueError("Not a syswow process")
        return windows.syswow64.get_current_process_syswow_peb()

    # TODO: use ctypes.string_ad / ctypes.wstring_at for read_string / read_wstring ? 
Example #12
Source File: winstring.py    From ArknightsAutoHelper with MIT License 5 votes vote down vote up
def __str__(self):
        if self.value is None:
            return ""
        length = ctypes.c_uint32()
        ptr = WindowsGetStringRawBuffer(self, ctypes.byref(length))
        return ctypes.wstring_at(ptr, length.value) 
Example #13
Source File: __init__.py    From EventGhost with GNU General Public License v2.0 4 votes vote down vote up
def Handler(self, hwnd, mesg, wParam, lParam):
        if not self.runFlg:
            return True
        cpyData = cast(lParam, PCOPYDATASTRUCT)
        cmd = cpyData.contents.dwData
        msg = wstring_at(cpyData.contents.lpData)
        if cmd == CMD_CONNECT:
            self.mpcHwnd = int(msg)
            self.connected = True
            eg.TriggerEvent("Connected",prefix="MPC-HC")
        elif cmd == CMD_STATE:
            state = int(msg)
            if self.state != state:
                self.state = state
                eg.TriggerEvent("State."+MPC_LOADSTATE[state],prefix="MPC-HC")
        elif cmd == CMD_NOWPLAYING:
            if self.playstate == 3: # if the plugin is started when the MPC-HC is already playing
                self.playstate = 0
            msg = self.ParseMsg(msg)
            if msg !=  self.np_payload:
                self.np_payload = msg
                eg.TriggerEvent("NowPlaying",prefix="MPC-HC", payload = msg)

        elif cmd == CMD_PLAYMODE:
            self.playstate = int(msg)
            eg.TriggerEvent("Playstate."+MPC_PLAYSTATE[self.playstate],prefix="MPC-HC")

        elif cmd == CMD_NOTIFYSEEK:
            eg.TriggerEvent("Seek",prefix="MPC-HC",payload = int(0.5+float(msg)))

        elif cmd in (
            CMD_CURRENTPOSITION,
            CMD_LISTSUBTITLETRACKS,
            CMD_LISTAUDIOTRACKS,
            CMD_PLAYLIST
        ):
            if self.event:
                self.result = self.ParseMsg(msg)
                SetEvent(self.event)

        elif cmd == CMD_NOTIFYENDOFSTREAM:
            eg.TriggerEvent("EndOfStream",prefix="MPC-HC")
        return True