我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用ctypes.wintypes.LPWSTR。
def __init__(self, console_handle, fileno, stream_name, encoding): super(WinUnicodeConsoleOutput, self).__init__( fileno, '<Unicode console %s>' % stream_name, encoding) # Handle to use for WriteConsoleW self._console_handle = console_handle # Loads the necessary function. # These types are available on linux but not Mac. # pylint: disable=no-name-in-module,F0401 from ctypes import byref, GetLastError, POINTER, windll, WINFUNCTYPE from ctypes.wintypes import BOOL, DWORD, HANDLE, LPWSTR from ctypes.wintypes import LPVOID # pylint: disable=no-name-in-module self._DWORD = DWORD self._byref = byref # <http://msdn.microsoft.com/en-us/library/ms687401.aspx> self._WriteConsoleW = WINFUNCTYPE( BOOL, HANDLE, LPWSTR, DWORD, POINTER(DWORD), LPVOID)( ('WriteConsoleW', windll.kernel32)) self._GetLastError = GetLastError
def win32_unicode_argv(): from ctypes import POINTER, byref, cdll, c_int, windll from ctypes.wintypes import LPCWSTR, LPWSTR GetCommandLineW = cdll.kernel32.GetCommandLineW GetCommandLineW.argtypes = [] GetCommandLineW.restype = LPCWSTR CommandLineToArgvW = windll.shell32.CommandLineToArgvW CommandLineToArgvW.argtypes = [LPCWSTR, POINTER(c_int)] CommandLineToArgvW.restype = POINTER(LPWSTR) cmd = GetCommandLineW() argc = c_int(0) argv = CommandLineToArgvW(cmd, byref(argc)) if argc.value > 0: # Remove Python executable and commands if present argc_value = int(argc.value) sys.argv = argv[argc_value-len(sys.argv):argc_value] # Run from command line
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 check_aslr(): # first check for a potentially rebased user32.dll from ctypes import windll from ctypes import wintypes check_dlls = ["user32.dll", "kernel32.dll", "ntdll.dll"] offsets = [] is_aslr = False windll.kernel32.GetModuleHandleW.restype = wintypes.HMODULE windll.kernel32.GetModuleHandleW.argtypes = [wintypes.LPCWSTR] windll.kernel32.GetModuleFileNameW.restype = wintypes.DWORD windll.kernel32.GetModuleFileNameW.argtypes = [wintypes.HANDLE, wintypes.LPWSTR, wintypes.DWORD] for dll_name in check_dlls: h_module_base = windll.kernel32.GetModuleHandleW(dll_name) # next get the module's file path module_path = wintypes.create_unicode_buffer(255) windll.kernel32.GetModuleFileNameW(h_module_base, module_path, 255) # then the ImageBase from python.exe file pe = pefile.PE(module_path.value) pe_header_base_addr = pe.OPTIONAL_HEADER.ImageBase offsets.append(pe_header_base_addr - h_module_base) for dll_name, offset in zip(check_dlls, offsets): LOG.debug("Memory vs. File ImageBase offset (%s): 0x%x", dll_name, offset) is_aslr |= offset != 0 return is_aslr
def getShortWindowsPath(long_name): """ Gets the short path name of a given long path. http://stackoverflow.com/a/23598461/200291 """ import ctypes from ctypes import wintypes _GetShortPathNameW = ctypes.windll.kernel32.GetShortPathNameW _GetShortPathNameW.argtypes = [wintypes.LPCWSTR, wintypes.LPWSTR, wintypes.DWORD] _GetShortPathNameW.restype = wintypes.DWORD output_buf_size = 0 while True: output_buf = ctypes.create_unicode_buffer(output_buf_size) needed = _GetShortPathNameW(long_name, output_buf, output_buf_size) if output_buf_size >= needed: return output_buf.value else: output_buf_size = needed
def win32_unicode_argv(): # type: () -> List[str] """Uses shell32.GetCommandLineArgvW to get sys.argv as a list of Unicode strings. Versions 2.x of Python don't support Unicode in sys.argv on Windows, with the underlying Windows API instead replacing multi-byte characters with '?'. """ from ctypes import POINTER, byref, cdll, c_int, windll from ctypes.wintypes import LPCWSTR, LPWSTR GetCommandLineW = cdll.kernel32.GetCommandLineW GetCommandLineW.argtypes = [] GetCommandLineW.restype = LPCWSTR CommandLineToArgvW = windll.shell32.CommandLineToArgvW CommandLineToArgvW.argtypes = [LPCWSTR, POINTER(c_int)] CommandLineToArgvW.restype = POINTER(LPWSTR) cmd = GetCommandLineW() argc = c_int(0) argv = CommandLineToArgvW(cmd, byref(argc)) if argc.value > 0: # Remove Python executable and commands if present start = argc.value - len(sys.argv) return [argv[i] for i in range(start, argc.value)] # ----------------------------------------------------------------------
def WlanGetProfile(hClientHandle, pInterfaceGuid, profileName): """ The WlanGetProfile function retrieves all information about a specified wireless profile. DWORD WINAPI WlanGetProfile( _In_ HANDLE hClientHandle, _In_ const GUID *pInterfaceGuid, _In_ LPCWSTR strProfileName, _Reserved_ PVOID pReserved, _Out_ LPWSTR *pstrProfileXml, _Inout_opt_ DWORD *pdwFlags, _Out_opt_ PDWORD pdwGrantedAccess ); """ func_ref = wlanapi.WlanGetProfile func_ref.argtypes = [HANDLE, POINTER(GUID), LPCWSTR, c_void_p, POINTER(LPWSTR), POINTER(DWORD), POINTER(DWORD)] func_ref.restype = DWORD pdw_granted_access = DWORD() xml = LPWSTR() flags = DWORD(WLAN_PROFILE_GET_PLAINTEXT_KEY) result = func_ref(hClientHandle, byref(pInterfaceGuid), profileName, None, byref(xml), byref(flags), byref(pdw_granted_access)) if result != ERROR_SUCCESS: raise Exception("WlanGetProfile failed.") return xml
def __init__(self, tzres_loc='tzres.dll'): # Load the user32 DLL so we can load strings from tzres user32 = ctypes.WinDLL('user32') # Specify the LoadStringW function user32.LoadStringW.argtypes = (wintypes.HINSTANCE, wintypes.UINT, wintypes.LPWSTR, ctypes.c_int) self.LoadStringW = user32.LoadStringW self._tzres = ctypes.WinDLL(tzres_loc) self.tzres_loc = tzres_loc
def windows_split_command_line(command): from ctypes import windll, c_int, POINTER, byref from ctypes.wintypes import LPCWSTR, LPWSTR, HLOCAL CommandLineToArgvW = windll.shell32.CommandLineToArgvW CommandLineToArgvW.argtypes = [LPCWSTR, POINTER(c_int)] CommandLineToArgvW.restype = POINTER(LPWSTR) LocalFree = windll.kernel32.LocalFree LocalFree.argtypes = [HLOCAL] LocalFree.restype = HLOCAL argc = c_int(0) argv = CommandLineToArgvW(command, byref(argc)) if not argv: # The docs say CommandLineToArgvW returns NULL on error, but they # don't describe any possible errors, so who knows when/if this happens. # Maybe only on low memory or something? raise WindowsCommandLineException("Windows could not parse command line: " + str(command)) try: result = [] i = 0 while i < argc.value: try: result.append(str(argv[i])) except UnicodeEncodeError as e: message = ( "Windows cannot represent this command line in its character encoding: " + command + ": " + str(e)) raise WindowsCommandLineException(message) i += 1 finally: LocalFree(argv) return result
def genwinmap(codepage): MultiByteToWideChar = ctypes.windll.kernel32.MultiByteToWideChar MultiByteToWideChar.argtypes = [wintypes.UINT, wintypes.DWORD, wintypes.LPCSTR, ctypes.c_int, wintypes.LPWSTR, ctypes.c_int] MultiByteToWideChar.restype = ctypes.c_int enc2uni = {} for i in range(32) + [127]: enc2uni[i] = (i, 'CONTROL CHARACTER') for i in range(256): buf = ctypes.create_unicode_buffer(2) ret = MultiByteToWideChar( codepage, 0, chr(i), 1, buf, 2) assert ret == 1, "invalid code page" assert buf[1] == '\x00' try: name = unicodedata.name(buf[0]) except ValueError: try: name = enc2uni[i][1] except KeyError: name = '' enc2uni[i] = (ord(buf[0]), name) return enc2uni
def win32_utf8_argv(): """Uses shell32.GetCommandLineArgvW to get sys.argv as a list of Unicode strings. Versions 2.x of Python don't support Unicode in sys.argv on Windows, with the underlying Windows API instead replacing multi-byte characters with '?'. """ from ctypes import POINTER, byref, cdll, c_int, windll from ctypes.wintypes import LPCWSTR, LPWSTR GetCommandLineW = cdll.kernel32.GetCommandLineW GetCommandLineW.argtypes = [] GetCommandLineW.restype = LPCWSTR CommandLineToArgvW = windll.shell32.CommandLineToArgvW CommandLineToArgvW.argtypes = [LPCWSTR, POINTER(c_int)] CommandLineToArgvW.restype = POINTER(LPWSTR) cmd = GetCommandLineW() argc = c_int(0) argv = CommandLineToArgvW(cmd, byref(argc)) argnum = argc.value sysnum = len(sys.argv) result = [] if argnum > 0: # Remove Python executable and commands if present start = argnum - sysnum for i in range(start, argnum): result.append(argv[i].encode('utf-8')) return result # enable unicode output to windows console # https://stackoverflow.com/questions/878972/windows-cmd-encoding-change-causes-python-crash
def CryptUnprotectData(data, optional_entropy=None, prompt_struct=None, flags=0): """ Returns a tuple of (description, data) where description is the the description that was passed to the CryptProtectData call and data is the decrypted result. """ data_in = DATA_BLOB(data) entropy = DATA_BLOB(optional_entropy) if optional_entropy else None data_out = DATA_BLOB() ptr_description = wintypes.LPWSTR() res = _CryptUnprotectData( data_in, ctypes.byref(ptr_description), entropy, None, # reserved prompt_struct, flags | CRYPTPROTECT_UI_FORBIDDEN, data_out, ) handle_nonzero_success(res) description = ptr_description.value if ptr_description.value is not None: ctypes.windll.kernel32.LocalFree(ptr_description) res = data_out.get_data() data_out.free() return description, res
def __init__(self, folder): self.folder = folder # Check the best way to do atomic file replacement. if sys.version_info >= (3, 3): self.replace = os.replace elif sys.platform == "win32": import ctypes from ctypes import wintypes ReplaceFile = ctypes.windll.kernel32.ReplaceFileW ReplaceFile.restype = wintypes.BOOL ReplaceFile.argtypes = [ wintypes.LPWSTR, wintypes.LPWSTR, wintypes.LPWSTR, wintypes.DWORD, wintypes.LPVOID, wintypes.LPVOID, ] def replace_windows(src, dst): if not ReplaceFile(dst, src, None, 0, 0, 0): os.rename(src, dst) self.replace = replace_windows else: # POSIX rename() is always atomic self.replace = os.rename