Python ctypes.c_wchar() Examples

The following are 30 code examples of ctypes.c_wchar(). 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: test_null_terminated_string.py    From zugbruecke with GNU Lesser General Public License v2.1 6 votes vote down vote up
def __init__(self):

		self.__dll__ = ctypes.windll.LoadLibrary('tests/demo_dll.dll')

		self.__replace_letter_in_null_terminated_string_unicode__ = self.__dll__.replace_letter_in_null_terminated_string_unicode_b
		self.__replace_letter_in_null_terminated_string_unicode__.argtypes = (
			ctypes.c_wchar_p, # Use built-in wchar pointer type
			ctypes.c_wchar,
			ctypes.c_wchar
			)
		self.__replace_letter_in_null_terminated_string_unicode__.memsync = [
			{
				'p': [0],
				'n': True,
				'w': True
				}
			] 
Example #2
Source File: ansiterm.py    From 802.11ah-ns3 with GNU General Public License v2.0 6 votes vote down vote up
def clear_screen(self,param):
			mode=to_int(param,0)
			sbinfo=self.screen_buffer_info()
			if mode==1:
				clear_start=COORD(0,0)
				clear_length=sbinfo.CursorPosition.X*sbinfo.CursorPosition.Y
			elif mode==2:
				clear_start=COORD(0,0)
				clear_length=sbinfo.Size.X*sbinfo.Size.Y
				windll.kernel32.SetConsoleCursorPosition(self.hconsole,clear_start)
			else:
				clear_start=sbinfo.CursorPosition
				clear_length=((sbinfo.Size.X-sbinfo.CursorPosition.X)+sbinfo.Size.X*(sbinfo.Size.Y-sbinfo.CursorPosition.Y))
			chars_written=c_ulong()
			windll.kernel32.FillConsoleOutputCharacterW(self.hconsole,c_wchar(' '),clear_length,clear_start,byref(chars_written))
			windll.kernel32.FillConsoleOutputAttribute(self.hconsole,sbinfo.Attributes,clear_length,clear_start,byref(chars_written)) 
Example #3
Source File: windows.py    From mayhem with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def _get_image_base_by_name(self, name):
		peb_ldr_data = self.get_proc_attribute('peb_ldr_data')

		firstFLink = 0
		fLink = peb_ldr_data.InLoadOrderModuleList.Flink
		while fLink != firstFLink:
			firstFLink = peb_ldr_data.InLoadOrderModuleList.Flink
			module = wintypes.LDR_MODULE()

			m_k32.ReadProcessMemory(self.handle, fLink, ctypes.byref(module), ctypes.sizeof(module), 0)

			_base_dll_name = (ctypes.c_wchar * module.BaseDllName.MaximumLength)
			base_dll_name = _base_dll_name()

			m_k32.ReadProcessMemory(self.handle, module.BaseDllName.Buffer, base_dll_name, module.BaseDllName.Length + 2, 0)
			base_dll_name = base_dll_name[:(module.BaseDllName.Length / 2)]
			if name == base_dll_name:
				return module
			fLink = module.InLoadOrderModuleList.Flink
		return None 
Example #4
Source File: test_null_terminated_string.py    From zugbruecke with GNU Lesser General Public License v2.1 6 votes vote down vote up
def __init__(self):

		self.__dll__ = ctypes.windll.LoadLibrary('tests/demo_dll.dll')

		self.__replace_letter_in_null_terminated_string_unicode__ = self.__dll__.replace_letter_in_null_terminated_string_unicode_a
		self.__replace_letter_in_null_terminated_string_unicode__.argtypes = (
			ctypes.POINTER(ctypes.c_wchar), # Generate pointer to wchar manually
			ctypes.c_wchar,
			ctypes.c_wchar
			)
		self.__replace_letter_in_null_terminated_string_unicode__.memsync = [
			{
				'p': [0],
				'n': True,
				'w': True
				}
			] 
Example #5
Source File: ansiterm.py    From royal-chaos with MIT License 6 votes vote down vote up
def clear_screen(self,param):
			mode=to_int(param,0)
			sbinfo=self.screen_buffer_info()
			if mode==1:
				clear_start=COORD(0,0)
				clear_length=sbinfo.CursorPosition.X*sbinfo.CursorPosition.Y
			elif mode==2:
				clear_start=COORD(0,0)
				clear_length=sbinfo.Size.X*sbinfo.Size.Y
				windll.kernel32.SetConsoleCursorPosition(self.hconsole,clear_start)
			else:
				clear_start=sbinfo.CursorPosition
				clear_length=((sbinfo.Size.X-sbinfo.CursorPosition.X)+sbinfo.Size.X*(sbinfo.Size.Y-sbinfo.CursorPosition.Y))
			chars_written=c_ulong()
			windll.kernel32.FillConsoleOutputCharacterW(self.hconsole,c_wchar(' '),clear_length,clear_start,byref(chars_written))
			windll.kernel32.FillConsoleOutputAttribute(self.hconsole,sbinfo.Attributes,clear_length,clear_start,byref(chars_written)) 
Example #6
Source File: test_unicode.py    From Fluid-Designer with GNU General Public License v3.0 6 votes vote down vote up
def test_aswidecharstring(self):
        from _testcapi import unicode_aswidecharstring
        support.import_module('ctypes')
        from ctypes import c_wchar, sizeof

        wchar, size = unicode_aswidecharstring('abc')
        self.assertEqual(size, 3)
        self.assertEqual(wchar, 'abc\0')

        wchar, size = unicode_aswidecharstring('abc\0def')
        self.assertEqual(size, 7)
        self.assertEqual(wchar, 'abc\0def\0')

        nonbmp = chr(0x10ffff)
        if sizeof(c_wchar) == 2:
            nchar = 2
        else: # sizeof(c_wchar) == 4
            nchar = 1
        wchar, size = unicode_aswidecharstring(nonbmp)
        self.assertEqual(size, nchar)
        self.assertEqual(wchar, nonbmp + '\0') 
Example #7
Source File: test_unicode.py    From android_universal with MIT License 6 votes vote down vote up
def test_aswidecharstring(self):
        from _testcapi import unicode_aswidecharstring
        support.import_module('ctypes')
        from ctypes import c_wchar, sizeof

        wchar, size = unicode_aswidecharstring('abc')
        self.assertEqual(size, 3)
        self.assertEqual(wchar, 'abc\0')

        wchar, size = unicode_aswidecharstring('abc\0def')
        self.assertEqual(size, 7)
        self.assertEqual(wchar, 'abc\0def\0')

        nonbmp = chr(0x10ffff)
        if sizeof(c_wchar) == 2:
            nchar = 2
        else: # sizeof(c_wchar) == 4
            nchar = 1
        wchar, size = unicode_aswidecharstring(nonbmp)
        self.assertEqual(size, nchar)
        self.assertEqual(wchar, nonbmp + '\0')

    # Test PyUnicode_AsUCS4() 
Example #8
Source File: test_unicode.py    From ironpython3 with Apache License 2.0 6 votes vote down vote up
def test_aswidecharstring(self):
        from _testcapi import unicode_aswidecharstring
        support.import_module('ctypes')
        from ctypes import c_wchar, sizeof

        wchar, size = unicode_aswidecharstring('abc')
        self.assertEqual(size, 3)
        self.assertEqual(wchar, 'abc\0')

        wchar, size = unicode_aswidecharstring('abc\0def')
        self.assertEqual(size, 7)
        self.assertEqual(wchar, 'abc\0def\0')

        nonbmp = chr(0x10ffff)
        if sizeof(c_wchar) == 2:
            nchar = 2
        else: # sizeof(c_wchar) == 4
            nchar = 1
        wchar, size = unicode_aswidecharstring(nonbmp)
        self.assertEqual(size, nchar)
        self.assertEqual(wchar, nonbmp + '\0') 
Example #9
Source File: windows.py    From BoomER with GNU General Public License v3.0 6 votes vote down vote up
def _get_image_base_by_name(self, name):
        peb_ldr_data = self.get_proc_attribute('peb_ldr_data')

        firstFLink = 0
        fLink = peb_ldr_data.InLoadOrderModuleList.Flink
        while fLink != firstFLink:
            firstFLink = peb_ldr_data.InLoadOrderModuleList.Flink
            module = wintypes.LDR_MODULE()

            self.k32.ReadProcessMemory(self.handle, fLink, ctypes.byref(module), ctypes.sizeof(module), 0)

            _base_dll_name = (ctypes.c_wchar * module.BaseDllName.MaximumLength)
            base_dll_name = _base_dll_name()

            self.k32.ReadProcessMemory(self.handle, module.BaseDllName.Buffer, base_dll_name,
                                       module.BaseDllName.Length + 2, 0)
            base_dll_name = base_dll_name[:(module.BaseDllName.Length / 2)]
            if name == base_dll_name:
                return module
            fLink = module.InLoadOrderModuleList.Flink
        return None 
Example #10
Source File: _multi_proc.py    From pyresample with GNU Lesser General Public License v3.0 6 votes vote down vote up
def shmem_as_ndarray(raw_array):
    _ctypes_to_numpy = {
        ctypes.c_char: np.int8,
        ctypes.c_wchar: np.int16,
        ctypes.c_byte: np.int8,
        ctypes.c_ubyte: np.uint8,
        ctypes.c_short: np.int16,
        ctypes.c_ushort: np.uint16,
        ctypes.c_int: np.int32,
        ctypes.c_uint: np.int32,
        ctypes.c_long: np.int32,
        ctypes.c_ulong: np.int32,
        ctypes.c_float: np.float32,
        ctypes.c_double: np.float64
    }
    dtype = _ctypes_to_numpy[raw_array._type_]

    # The following works too, but occasionally raises
    # RuntimeWarning: Item size computed from the PEP 3118 buffer format string does not match the actual item size.
    # and appears to be slower.
    # return np.ctypeslib.as_array(raw_array)

    return np.frombuffer(raw_array, dtype=dtype) 
Example #11
Source File: test_unicode.py    From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 6 votes vote down vote up
def test_aswidecharstring(self):
        from _testcapi import unicode_aswidecharstring
        support.import_module('ctypes')
        from ctypes import c_wchar, sizeof

        wchar, size = unicode_aswidecharstring('abc')
        self.assertEqual(size, 3)
        self.assertEqual(wchar, 'abc\0')

        wchar, size = unicode_aswidecharstring('abc\0def')
        self.assertEqual(size, 7)
        self.assertEqual(wchar, 'abc\0def\0')

        nonbmp = chr(0x10ffff)
        if sizeof(c_wchar) == 2:
            nchar = 2
        else: # sizeof(c_wchar) == 4
            nchar = 1
        wchar, size = unicode_aswidecharstring(nonbmp)
        self.assertEqual(size, nchar)
        self.assertEqual(wchar, nonbmp + '\0')

    # Test PyUnicode_AsUCS4() 
Example #12
Source File: iscsi_utils.py    From os-win with Apache License 2.0 5 votes vote down vote up
def get_iscsi_initiator(self):
        """Returns the initiator node name."""
        try:
            buff = (ctypes.c_wchar * (w_const.MAX_ISCSI_NAME_LEN + 1))()
            self._run_and_check_output(iscsidsc.GetIScsiInitiatorNodeNameW,
                                       buff)
            return buff.value
        except exceptions.ISCSIInitiatorAPIException as ex:
            LOG.info("The ISCSI initiator node name can't be found. "
                     "Choosing the default one. Exception: %s", ex)
            return "%s:%s" % (self._MS_IQN_PREFIX, socket.getfqdn().lower()) 
Example #13
Source File: remotectypes.py    From PythonForWindows with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _handle_field_getattr(self, ftype, fosset, fsize):
        s = self._target.read_memory(self._base_addr + fosset, fsize)
        if ftype in self._field_type_to_remote_type:
            return self._field_type_to_remote_type[ftype].from_buffer_with_target(bytearray(s), target=self._target).value
        if issubclass(ftype, _ctypes._Pointer):  # Pointer
            return RemoteStructurePointer.from_buffer_with_target_and_ptr_type(bytearray(s), target=self._target, ptr_type=ftype)
        if issubclass(ftype, RemotePtr64):  # Pointer to remote64 bits process
            return RemoteStructurePointer64.from_buffer_with_target_and_ptr_type(bytearray(s), target=self._target, ptr_type=ftype)
        if issubclass(ftype, RemotePtr32):  # Pointer to remote32 bits process
            return RemoteStructurePointer32.from_buffer_with_target_and_ptr_type(bytearray(s), target=self._target, ptr_type=ftype)
        if issubclass(ftype, RemoteStructureUnion):  # Structure|Union already transfomed in remote
            return ftype(self._base_addr + fosset, self._target)
        if issubclass(ftype, ctypes.Structure):  # Structure that must be transfomed
            return RemoteStructure.from_structure(ftype)(self._base_addr + fosset, self._target)
        if issubclass(ftype, ctypes.Union):  # Union that must be transfomed
            return RemoteUnion.from_structure(ftype)(self._base_addr + fosset, self._target)
        if issubclass(ftype, _ctypes.Array):  # Arrays
            # if this is a string: just cast the read value to string
            if ftype._type_ == ctypes.c_char: # Use issubclass instead ?
                return s.split("\x00", 1)[0]
            elif ftype._type_ == ctypes.c_wchar: # Use issubclass instead ?
                # Decode from utf16 -> size /=2 | put it in a wchar array | split at the first "\x00"
                return (ftype._type_ * (fsize / 2)).from_buffer_copy(s.decode('utf16'))[:].split("\x00", 1)[0] # Sorry..
            # I am pretty sur something smarter is possible..
            return create_remote_array(ftype._type_, ftype._length_)(self._base_addr + fosset, self._target)
        # Normal types
        # Follow the ctypes usage: if it's not directly inherited from _SimpleCData
        # We do not apply the .value
        # Seems weird but it's mandatory AND useful :D (in pe_parse)
        if _SimpleCData not in ftype.__bases__:
            return ftype.from_buffer(bytearray(s))
        return ftype.from_buffer(bytearray(s)).value 
Example #14
Source File: iscsi_utils.py    From os-win with Apache License 2.0 5 votes vote down vote up
def _parse_string_list(buff, element_count):
        buff = ctypes.cast(buff, ctypes.POINTER(ctypes.c_wchar))
        str_list = buff[:element_count].strip('\x00')
        # Avoid returning a list with an empty string
        str_list = str_list.split('\x00') if str_list else []
        return str_list 
Example #15
Source File: test_clusapi_utils.py    From os-win with Apache License 2.0 5 votes vote down vote up
def test_get_cluster_group_state(self):
        owner_node = 'fake owner node'

        def fake_get_state(inst,
                           group_handle, node_name_buff, node_name_len,
                           error_ret_vals, error_on_nonzero_ret_val,
                           ret_val_is_err_code):
            self.assertEqual(mock.sentinel.group_handle, group_handle)

            # Those arguments would not normally get to the ClusApi
            # function, instead being used by the helper invoking
            # it and catching errors. For convenience, we validate
            # those arguments at this point.
            self.assertEqual([constants.CLUSTER_GROUP_STATE_UNKNOWN],
                             error_ret_vals)
            self.assertFalse(error_on_nonzero_ret_val)
            self.assertFalse(ret_val_is_err_code)

            node_name_len_arg = ctypes.cast(
                node_name_len,
                wintypes.PDWORD).contents
            self.assertEqual(w_const.MAX_PATH,
                             node_name_len_arg.value)

            node_name_arg = ctypes.cast(
                node_name_buff,
                ctypes.POINTER(
                    ctypes.c_wchar *
                    w_const.MAX_PATH)).contents
            node_name_arg.value = owner_node
            return mock.sentinel.group_state

        self._mock_run.side_effect = fake_get_state

        state_info = self._clusapi_utils.get_cluster_group_state(
            mock.sentinel.group_handle)
        expected_state_info = dict(state=mock.sentinel.group_state,
                                   owner_node=owner_node)
        self.assertEqual(expected_state_info, state_info) 
Example #16
Source File: test_iscsi_utils.py    From os-win with Apache License 2.0 5 votes vote down vote up
def test_get_items_from_buff(self):
        fake_buff_contents = 'fake_buff_contents'
        fake_buff = (ctypes.c_wchar * len(fake_buff_contents))()
        fake_buff.value = fake_buff_contents

        fake_buff = ctypes.cast(fake_buff, ctypes.POINTER(ctypes.c_ubyte))

        result = iscsi_utils._get_items_from_buff(fake_buff, ctypes.c_wchar,
                                                  len(fake_buff_contents))

        self.assertEqual(fake_buff_contents, result.value) 
Example #17
Source File: test_iscsi_utils.py    From os-win with Apache License 2.0 5 votes vote down vote up
def test_parse_string_list(self):
        self._mock_ctypes()

        fake_buff = 'fake\x00buff\x00\x00'
        self._ctypes.cast.return_value = fake_buff

        str_list = self._initiator._parse_string_list(fake_buff,
                                                      len(fake_buff))

        self.assertEqual(['fake', 'buff'], str_list)

        self._ctypes.cast.assert_called_once_with(
            fake_buff, self._ctypes.POINTER.return_value)
        self._ctypes.POINTER.assert_called_once_with(self._ctypes.c_wchar) 
Example #18
Source File: test_iscsi_utils.py    From os-win with Apache License 2.0 5 votes vote down vote up
def test_get_iscsi_initiator(self):
        self._mock_ctypes()

        self._ctypes.c_wchar = mock.MagicMock()
        fake_buff = (self._ctypes.c_wchar * (
            w_const.MAX_ISCSI_NAME_LEN + 1))()
        fake_buff.value = mock.sentinel.buff_value

        resulted_iscsi_initiator = self._initiator.get_iscsi_initiator()

        self._mock_run.assert_called_once_with(
            self._iscsidsc.GetIScsiInitiatorNodeNameW,
            fake_buff)
        self.assertEqual(mock.sentinel.buff_value,
                         resulted_iscsi_initiator) 
Example #19
Source File: xtf_ctypes.py    From pyxtf with MIT License 5 votes vote down vote up
def __str__(self):
        """
        Prints the fields in the class (with ctype-fields) in the order in which they appear in the structure.
        """
        fields = []
        for field_name in dir(self):
            if not field_name.startswith('_') and not field_name.endswith('_'):
                field_value = getattr(self, field_name)
                field_type = type(field_value)

                # callable(obj) will return true for the fields, using 'method' name instead
                if not field_type.__name__ == 'method':
                    if hasattr(self.__class__, field_name) and hasattr(getattr(self.__class__, field_name), 'offset'):
                        offset = getattr(self.__class__, field_name).offset
                    else:
                        offset = 2 ** 31

                    if ctypes.Array in field_type.__bases__ and field_type._type_ not in [ctypes.c_char, ctypes.c_wchar]:
                        if len(field_value) > 20:
                            val_str = field_value[:10] + ['...'] + field_value[-10:]
                        else:
                            val_str = list(field_value)
                        out_str = '{}: {}\n'.format(field_name, val_str)
                    else:
                        out_str = '{}: {}\n'.format(field_name, field_value)

                    fields.append((offset, out_str))

        # Sort by offset (non-ctypes placed last)
        fields.sort(key=lambda x: x[0])
        out = ''.join(field[1] for field in fields)

        return out 
Example #20
Source File: test_unicode.py    From android_universal with MIT License 5 votes vote down vote up
def test_aswidechar(self):
        from _testcapi import unicode_aswidechar
        support.import_module('ctypes')
        from ctypes import c_wchar, sizeof

        wchar, size = unicode_aswidechar('abcdef', 2)
        self.assertEqual(size, 2)
        self.assertEqual(wchar, 'ab')

        wchar, size = unicode_aswidechar('abc', 3)
        self.assertEqual(size, 3)
        self.assertEqual(wchar, 'abc')

        wchar, size = unicode_aswidechar('abc', 4)
        self.assertEqual(size, 3)
        self.assertEqual(wchar, 'abc\0')

        wchar, size = unicode_aswidechar('abc', 10)
        self.assertEqual(size, 3)
        self.assertEqual(wchar, 'abc\0')

        wchar, size = unicode_aswidechar('abc\0def', 20)
        self.assertEqual(size, 7)
        self.assertEqual(wchar, 'abc\0def\0')

        nonbmp = chr(0x10ffff)
        if sizeof(c_wchar) == 2:
            buflen = 3
            nchar = 2
        else: # sizeof(c_wchar) == 4
            buflen = 2
            nchar = 1
        wchar, size = unicode_aswidechar(nonbmp, buflen)
        self.assertEqual(size, nchar)
        self.assertEqual(wchar, nonbmp + '\0')

    # Test PyUnicode_AsWideCharString() 
Example #21
Source File: winauto.py    From SendCode with MIT License 5 votes vote down vote up
def get_class(hwnd):
    className = (c_wchar * 257)()
    GetClassName(hwnd, ctypes.byref(className), 256)
    return className.value 
Example #22
Source File: mem_contents.py    From zugbruecke with GNU Lesser General Public License v2.1 5 votes vote down vote up
def __get_length_of_null_terminated_string__(self, in_pointer, is_unicode):

		if is_unicode:
			datatype = ctypes.c_wchar
			datatype_p = ctypes.c_wchar_p
		else:
			datatype = ctypes.c_char
			datatype_p = ctypes.c_char_p

		return len(ctypes.cast(in_pointer, datatype_p).value) * ctypes.sizeof(datatype) 
Example #23
Source File: vhdutils.py    From os-win with Apache License 2.0 5 votes vote down vote up
def get_virtual_disk_physical_path(self, vhd_path):
        """Returns the physical disk path for an attached disk image.

        :param vhd_path: an attached disk image path.
        :returns: the mount path of the specified image, in the form of
                  \\\\.\\PhysicalDriveX.
        """

        open_flag = w_const.OPEN_VIRTUAL_DISK_FLAG_NO_PARENTS
        open_access_mask = (w_const.VIRTUAL_DISK_ACCESS_GET_INFO |
                            w_const.VIRTUAL_DISK_ACCESS_DETACH)
        handle = self._open(
            vhd_path,
            open_flag=open_flag,
            open_access_mask=open_access_mask)

        disk_path = (ctypes.c_wchar * w_const.MAX_PATH)()
        disk_path_sz = wintypes.ULONG(w_const.MAX_PATH)
        self._run_and_check_output(
            virtdisk.GetVirtualDiskPhysicalPath,
            handle,
            ctypes.byref(disk_path_sz),
            disk_path,
            cleanup_handle=handle)

        return disk_path.value 
Example #24
Source File: _clusapi_utils.py    From os-win with Apache License 2.0 5 votes vote down vote up
def get_cluster_group_state(self, group_handle):
        node_name_len = wintypes.DWORD(w_const.MAX_PATH)
        node_name_buff = (ctypes.c_wchar * node_name_len.value)()

        group_state = self._run_and_check_output(
            clusapi.GetClusterGroupState,
            group_handle,
            node_name_buff,
            ctypes.byref(node_name_len),
            error_ret_vals=[constants.CLUSTER_GROUP_STATE_UNKNOWN],
            error_on_nonzero_ret_val=False,
            ret_val_is_err_code=False)

        return {'state': group_state,
                'owner_node': node_name_buff.value} 
Example #25
Source File: _clusapi_utils.py    From os-win with Apache License 2.0 5 votes vote down vote up
def get_property_list_entry(self, name, syntax, value):
        # The value argument must have a ctypes type.
        name_len = len(name) + 1
        val_sz = ctypes.sizeof(value)

        class CLUSPROP_LIST_ENTRY(ctypes.Structure):
            _fields_ = [
                ('name', self._get_clusprop_value_struct(
                    val_type=ctypes.c_wchar * name_len)),
                ('value', self._get_clusprop_value_struct(
                    val_type=ctypes.c_ubyte * val_sz)),
                ('_endmark', wintypes.DWORD)
            ]

        entry = CLUSPROP_LIST_ENTRY()
        entry.name.syntax = w_const.CLUSPROP_SYNTAX_NAME
        entry.name.length = name_len * ctypes.sizeof(ctypes.c_wchar)
        entry.name.value = name

        entry.value.syntax = syntax
        entry.value.length = val_sz
        entry.value.value[0:val_sz] = bytearray(value)

        entry._endmark = w_const.CLUSPROP_SYNTAX_ENDMARK

        return entry 
Example #26
Source File: win32_window.py    From dragonfly with GNU Lesser General Public License v3.0 5 votes vote down vote up
def _get_window_module(self):
        # Get this window's process ID.
        pid = self._get_window_pid()

        # Get the process handle of this window's process ID.
        #  Access permission flags:
        #  0x0410 = PROCESS_QUERY_INFORMATION | PROCESS_VM_READ
        handle = windll.kernel32.OpenProcess(0x0410, 0, pid)

        # Retrieve and return the process's executable path.
        try:
            # Try to use the QueryForProcessImageNameW function
            #  available since Windows Vista.
            buffer_len = c_ulong(256)
            buffer = (c_wchar * buffer_len.value)()
            windll.kernel32.QueryFullProcessImageNameW(handle, 0,
                                                       pointer(buffer),
                                                       pointer(buffer_len))
            buffer = buffer[:]
            buffer = buffer[:buffer.index("\0")]
        except Exception:
            # If the function above failed, fall back to the older
            #  GetModuleFileNameEx function, available since windows XP.
            #  Note that this fallback function seems to fail when
            #  this process is 32 bit Python and handle refers to a
            #  64-bit process.
            buffer_len = 256
            buffer = (c_wchar * buffer_len)()
            windll.psapi.GetModuleFileNameExW(handle, 0, pointer(buffer),
                                              buffer_len)
            buffer = buffer[:]
            buffer = buffer[:buffer.index("\0")]
        finally:
            windll.kernel32.CloseHandle(handle)

        return str(buffer)

    #-----------------------------------------------------------------------
    # Methods related to window geometry. 
Example #27
Source File: test_unicode.py    From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 5 votes vote down vote up
def test_aswidechar(self):
        from _testcapi import unicode_aswidechar
        support.import_module('ctypes')
        from ctypes import c_wchar, sizeof

        wchar, size = unicode_aswidechar('abcdef', 2)
        self.assertEqual(size, 2)
        self.assertEqual(wchar, 'ab')

        wchar, size = unicode_aswidechar('abc', 3)
        self.assertEqual(size, 3)
        self.assertEqual(wchar, 'abc')

        wchar, size = unicode_aswidechar('abc', 4)
        self.assertEqual(size, 3)
        self.assertEqual(wchar, 'abc\0')

        wchar, size = unicode_aswidechar('abc', 10)
        self.assertEqual(size, 3)
        self.assertEqual(wchar, 'abc\0')

        wchar, size = unicode_aswidechar('abc\0def', 20)
        self.assertEqual(size, 7)
        self.assertEqual(wchar, 'abc\0def\0')

        nonbmp = chr(0x10ffff)
        if sizeof(c_wchar) == 2:
            buflen = 3
            nchar = 2
        else: # sizeof(c_wchar) == 4
            buflen = 2
            nchar = 1
        wchar, size = unicode_aswidechar(nonbmp, buflen)
        self.assertEqual(size, nchar)
        self.assertEqual(wchar, nonbmp + '\0')

    # Test PyUnicode_AsWideCharString() 
Example #28
Source File: win32_file_watcher.py    From python-compat-runtime with Apache License 2.0 5 votes vote down vote up
def _parse_file_notification_information(buff, offset):
  """Parse FileNotificationInformation from a c_char buffer.

  Args:
    buff: a ctypes string buffer that contains
         a FileNotificationInformation structure.
    offset: the offset you want to parse the struct from.

  Returns:
    a class matching the structure.
  """
  notify_information_short = ctypes.cast(
      ctypes.addressof(buff) + offset,
      ctypes.POINTER(FileNotifyInformationShort)).contents
  # This is a variable length structure so we need to do a 2 steps parse to
  # create a perfectly matching result.
  chr_len = notify_information_short.FileNameLength / _WCHAR_BYTESIZE

  class FileNotifyInformation(ctypes.Structure):
    _fields_ = (
        _COMMON_FILE_NOTIFY_FIELDS +
        [('FileName', ctypes.c_wchar * chr_len)])
  return ctypes.cast(ctypes.addressof(buff) + offset,
                     ctypes.POINTER(FileNotifyInformation)).contents


# we want to be sure that at least one notification fits even if it is a big
# one. 
Example #29
Source File: test_unicode.py    From ironpython3 with Apache License 2.0 5 votes vote down vote up
def test_aswidechar(self):
        from _testcapi import unicode_aswidechar
        support.import_module('ctypes')
        from ctypes import c_wchar, sizeof

        wchar, size = unicode_aswidechar('abcdef', 2)
        self.assertEqual(size, 2)
        self.assertEqual(wchar, 'ab')

        wchar, size = unicode_aswidechar('abc', 3)
        self.assertEqual(size, 3)
        self.assertEqual(wchar, 'abc')

        wchar, size = unicode_aswidechar('abc', 4)
        self.assertEqual(size, 3)
        self.assertEqual(wchar, 'abc\0')

        wchar, size = unicode_aswidechar('abc', 10)
        self.assertEqual(size, 3)
        self.assertEqual(wchar, 'abc\0')

        wchar, size = unicode_aswidechar('abc\0def', 20)
        self.assertEqual(size, 7)
        self.assertEqual(wchar, 'abc\0def\0')

        nonbmp = chr(0x10ffff)
        if sizeof(c_wchar) == 2:
            buflen = 3
            nchar = 2
        else: # sizeof(c_wchar) == 4
            buflen = 2
            nchar = 1
        wchar, size = unicode_aswidechar(nonbmp, buflen)
        self.assertEqual(size, nchar)
        self.assertEqual(wchar, nonbmp + '\0')

    # Test PyUnicode_AsWideCharString() 
Example #30
Source File: window.py    From dragonfly with GNU Lesser General Public License v3.0 5 votes vote down vote up
def _get_window_module(self):
        # Get this window's process ID.
        pid = c_ulong()
        windll.user32.GetWindowThreadProcessId(self._handle, pointer(pid))

        # Get the process handle of this window's process ID.
        #  Access permission flags:
        #  0x0410 = PROCESS_QUERY_INFORMATION | PROCESS_VM_READ
        handle = windll.kernel32.OpenProcess(0x0410, 0, pid)

        # Retrieve and return the process's executable path.
        try:
            # Try to use the QueryForProcessImageNameW function
            #  available since Windows Vista.
            buffer_len = c_ulong(256)
            buffer = (c_wchar * buffer_len.value)()
            windll.kernel32.QueryFullProcessImageNameW(handle, 0,
                                                       pointer(buffer),
                                                       pointer(buffer_len))
            buffer = buffer[:]
            buffer = buffer[:buffer.index("\0")]
        except Exception:
            # If the function above failed, fall back to the older
            #  GetModuleFileNameEx function, available since windows XP.
            #  Note that this fallback function seems to fail when
            #  this process is 32 bit Python and handle refers to a
            #  64-bit process.
            buffer_len = 256
            buffer = (c_wchar * buffer_len)()
            windll.psapi.GetModuleFileNameExW(handle, 0, pointer(buffer),
                                              buffer_len)
            buffer = buffer[:]
            buffer = buffer[:buffer.index("\0")]
        finally:
            windll.kernel32.CloseHandle(handle)

        return str(buffer)