我们从Python开源项目中,提取了以下28个代码示例,用于说明如何使用ctypes.c_wchar()。
def clip_files(file_list): offset = ctypes.sizeof(DROPFILES) length = sum(len(p) + 1 for p in file_list) + 1 size = offset + length * ctypes.sizeof(ctypes.c_wchar) buf = (ctypes.c_char * size)() df = DROPFILES.from_buffer(buf) df.pFiles, df.fWide = offset, True for path in file_list: path = path.decode('gbk') print "copying to clipboard, filename = " + path array_t = ctypes.c_wchar * (len(path) + 1) path_buf = array_t.from_buffer(buf, offset) path_buf.value = path offset += ctypes.sizeof(path_buf) stg = pythoncom.STGMEDIUM() stg.set(pythoncom.TYMED_HGLOBAL, buf) win32clipboard.OpenClipboard() win32clipboard.EmptyClipboard() try: win32clipboard.SetClipboardData(win32clipboard.CF_HDROP, stg.data) print "clip_files() succeed" finally: win32clipboard.CloseClipboard()
def clear_screen(self, param): mode = to_int(param, 0) sbinfo = self.screen_buffer_info() if mode == 1: # Clear from begining of screen to cursor position clear_start = COORD(0, 0) clear_length = sbinfo.CursorPosition.X * sbinfo.CursorPosition.Y elif mode == 2: # Clear entire screen and return cursor to home clear_start = COORD(0, 0) clear_length = sbinfo.Size.X * sbinfo.Size.Y windll.kernel32.SetConsoleCursorPosition(self.hconsole, clear_start) else: # Clear from cursor position to end of screen 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))
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 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')
def __init__(self, buffer_size=1024): """Builds the tracing session properties. Parameters --------- buffer_size: int the amount of memory allocated for each trace buffer """ # allocate buffer for the trace self.max_string_len = 1024 self.buff_size = sizeof(EVENT_TRACE_PROPERTIES) + 2 * sizeof(c_wchar) * self.max_string_len self._buff = (c_char * self.buff_size)() self._props = cast(pointer(self._buff), POINTER(EVENT_TRACE_PROPERTIES)) # set trace properties self._props.contents.wnode.buffer_size = self.buff_size self._props.contents.wnode.guid = KERNEL_TRACE_CONTROL_GUID self._props.contents.wnode.flags = WNODE_FLAG_TRACED_GUID self._props.contents.logger_name_offset = sizeof(EVENT_TRACE_PROPERTIES) self._props.contents.log_file_name_offset = 0 self._props.contents.log_file_mode = PROCESS_TRACE_MODE_REAL_TIME self._props.contents.buffer_size = buffer_size
def clear_line(self, param): mode = param and int(param) or 0 sbinfo = self.screen_buffer_info() if mode == 1: # Clear from begining of line to cursor position line_start = COORD(0, sbinfo.CursorPosition.Y) line_length = sbinfo.Size.X elif mode == 2: # Clear entire line line_start = COORD(sbinfo.CursorPosition.X, sbinfo.CursorPosition.Y) line_length = sbinfo.Size.X - sbinfo.CursorPosition.X else: # Clear from cursor position to end of line line_start = sbinfo.CursorPosition line_length = sbinfo.Size.X - sbinfo.CursorPosition.X chars_written = c_ulong() windll.kernel32.FillConsoleOutputCharacterW(self.hconsole, c_wchar(' '), line_length, line_start, byref(chars_written)) windll.kernel32.FillConsoleOutputAttribute(self.hconsole, sbinfo.Attributes, line_length, line_start, byref(chars_written))
def str(self): """The python string of the LSA_UNICODE_STRING object :type: :class:`unicode` """ if not self.Length: return "" if getattr(self, "_target", None) is not None: #remote ctypes :D -> TRICKS OF THE YEAR raw_data = self._target.read_memory(self.Buffer, self.Length) return raw_data.decode("utf16") size = self.Length / 2 return (ctypes.c_wchar * size).from_address(self.Buffer)[:]
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
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 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()
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.
def logger_name(self, logger_name): name_len = len(logger_name) + 1 if self.max_string_len < name_len: raise ArgumentError("Logger name %s is too long" % logger_name) props = self._props logger = c_wchar_p(addressof(props.contents) + props.contents.logger_name_offset) memmove(logger, c_wchar_p(logger_name), sizeof(c_wchar) * name_len)
def fixed_install_font(src_path): # copy the font to the Windows Fonts folder dst_path = os.path.join( os.environ['SystemRoot'], 'Fonts', os.path.basename(src_path) ) shutil.copy(src_path, dst_path) # load the font in the current session if not gdi32.AddFontResourceW(dst_path): os.remove(dst_path) raise WindowsError('AddFontResource failed to load "%s"' % src_path) # notify running programs user32.SendMessageTimeoutW( HWND_BROADCAST, WM_FONTCHANGE, 0, 0, SMTO_ABORTIFHUNG, 1000, None ) # store the fontname/filename in the registry filename = os.path.basename(dst_path) fontname = os.path.splitext(filename)[0] # try to get the font's real name cb = wintypes.DWORD() if gdi32.GetFontResourceInfoW( filename, ctypes.byref(cb), None, GFRI_DESCRIPTION ): buf = (ctypes.c_wchar * cb.value)() if gdi32.GetFontResourceInfoW( filename, ctypes.byref(cb), buf, GFRI_DESCRIPTION ): fontname = buf.value is_truetype = wintypes.BOOL() cb.value = ctypes.sizeof(is_truetype) gdi32.GetFontResourceInfoW( filename, ctypes.byref(cb), ctypes.byref(is_truetype), GFRI_ISTRUETYPE ) if is_truetype: fontname += ' (TrueType)' with winreg.OpenKey( winreg.HKEY_LOCAL_MACHINE, FONTS_REG_PATH, 0, winreg.KEY_SET_VALUE ) as key: winreg.SetValueEx(key, fontname, 0, winreg.REG_SZ, filename)