我们从Python开源项目中,提取了以下26个代码示例,用于说明如何使用ctypes.wintypes.LPCWSTR。
def WlanDeleteProfile(hClientHandle, pInterfaceGuid, profileName): """ DWORD WINAPI WlanDeleteProfile( _In_ HANDLE hClientHandle, _In_ const GUID *pInterfaceGuid, _In_ LPCWSTR strProfileName, _Reserved_ PVOID pReserved ); """ func_ref = wlanapi.WlanDeleteProfile func_ref.argtypes = [HANDLE, POINTER(GUID), LPCWSTR, c_void_p] func_ref.restype = DWORD result = func_ref(hClientHandle, byref(pInterfaceGuid), profileName, None) if result != ERROR_SUCCESS: raise Exception("WlanDeleteProfile failed. error %d" % result, result) return result
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 send2trash(path): if not isinstance(path, text_type): path = text_type(path, 'mbcs') if not op.isabs(path): path = op.abspath(path) fileop = SHFILEOPSTRUCTW() fileop.hwnd = 0 fileop.wFunc = FO_DELETE fileop.pFrom = LPCWSTR(path + '\0') fileop.pTo = None fileop.fFlags = FOF_ALLOWUNDO | FOF_NOCONFIRMATION | FOF_NOERRORUI | FOF_SILENT fileop.fAnyOperationsAborted = 0 fileop.hNameMappings = 0 fileop.lpszProgressTitle = None result = SHFileOperationW(byref(fileop)) if result: msg = "Couldn't perform operation. Error code: %d" % result raise OSError(msg)
def send2trash(path): # #if not isinstance(path, str): # path = str(path, 'mbcs') #if not op.isabs(path): # path = op.abspath(path) fileop = SHFILEOPSTRUCTW() fileop.hwnd = 0 fileop.wFunc = FO_DELETE fileop.pFrom = LPCWSTR(path + '\0') fileop.pTo = None fileop.fFlags = FOF_ALLOWUNDO | FOF_NOCONFIRMATION | FOF_NOERRORUI | FOF_SILENT fileop.fAnyOperationsAborted = 0 fileop.hNameMappings = 0 fileop.lpszProgressTitle = None result = SHFileOperationW(byref(fileop)) if result: msg = "Couldn't perform operation. Error code: %d" % result raise OSError(msg)
def arg_split(commandline, posix=False, strict=True): """Split a command line's arguments in a shell-like manner. This is a special version for windows that use a ctypes call to CommandLineToArgvW to do the argv splitting. The posix paramter is ignored. If strict=False, process_common.arg_split(...strict=False) is used instead. """ #CommandLineToArgvW returns path to executable if called with empty string. if commandline.strip() == "": return [] if not strict: # not really a cl-arg, fallback on _process_common return py_arg_split(commandline, posix=posix, strict=strict) argvn = c_int() result_pointer = CommandLineToArgvW(py3compat.cast_unicode(commandline.lstrip()), ctypes.byref(argvn)) result_array_type = LPCWSTR * argvn.value result = [arg for arg in result_array_type.from_address(ctypes.addressof(result_pointer.contents))] retval = LocalFree(result_pointer) return result
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 __init__ (self): import ctypes.wintypes if sys.platform[:3] != 'win': raise SystemError('Windows is required') self.__winmm = ctypes.windll.LoadLibrary('winmm.dll') self.__mciSendStringW = self.__winmm.mciSendStringW self.__mciGetErrorStringW = self.__winmm.mciGetErrorStringW wintypes = ctypes.wintypes LPCWSTR, HANDLE = wintypes.LPCWSTR, wintypes.HANDLE args = [LPCWSTR, ctypes.c_char_p, wintypes.UINT, HANDLE] self.__mciSendStringW.argtypes = args self.__mciSendStringW.restype = wintypes.DWORD args = [wintypes.DWORD, ctypes.c_void_p, wintypes.UINT] self.__mciGetErrorStringW.argtypes = args self.__mciGetErrorStringW.restype = wintypes.BOOL self.__buffer = ctypes.create_string_buffer('?' * 4098) self.__alias_index = 0
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 get(intFolder): _SHGetFolderPath.argtypes = [_HWND, _ctypes.c_int, _HANDLE, _DWORD, _LPCWSTR] auPathBuffer = _cub(_MAX_PATH) exit_code=_SHGetFolderPath(0, intFolder, 0, 0, auPathBuffer) return auPathBuffer.value
def _link(src, dst, linktype=LINK_HARD): if linktype == LINK_HARD: if on_win: from ctypes import windll, wintypes CreateHardLink = windll.kernel32.CreateHardLinkW CreateHardLink.restype = wintypes.BOOL CreateHardLink.argtypes = [wintypes.LPCWSTR, wintypes.LPCWSTR, wintypes.LPVOID] if not CreateHardLink(dst, src, None): raise OSError('win32 hard link failed') else: os.link(src, dst) elif linktype == LINK_COPY: # copy relative symlinks as symlinks if islink(src) and not os.readlink(src).startswith(os.path.sep): os.symlink(os.readlink(src), dst) else: shutil.copy2(src, dst) else: raise Exception("Did not expect linktype=%r" % linktype)
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 get_user_config_dir(): """Platform specific directory for user configuration. :returns: returns the user configuration directory. :rtype: string """ if os.name == 'nt': try: csidl_appdata = 26 shgetfolderpath = windll.shell32.SHGetFolderPathW shgetfolderpath.argtypes = [wintypes.HWND, ctypes.c_int, \ wintypes.HANDLE, wintypes.DWORD, wintypes.LPCWSTR] path_buf = wintypes.create_unicode_buffer(wintypes.MAX_PATH) result = shgetfolderpath(0, csidl_appdata, 0, 0, path_buf) if result == 0: return path_buf.value except ImportError: pass return os.environ['APPDATA'] else: return os.path.expanduser('~')
def __init__(self, dict): if not dict: self._as_parameter_ = None else: values = ["%s=%s" % (key, value) for (key, value) in dict.items()] values.append("") self._as_parameter_ = LPCWSTR("\0".join(values)) # CreateProcess()
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 fix_win_sys_argv(encoding): """Converts sys.argv to 'encoding' encoded string. utf-8 is recommended. Works around <http://bugs.python.org/issue2128>. """ global _SYS_ARGV_PROCESSED if _SYS_ARGV_PROCESSED: return False # These types are available on linux but not Mac. # pylint: disable=no-name-in-module,F0401 from ctypes import byref, c_int, POINTER, windll, WINFUNCTYPE from ctypes.wintypes import LPCWSTR, LPWSTR # <http://msdn.microsoft.com/en-us/library/ms683156.aspx> GetCommandLineW = WINFUNCTYPE(LPWSTR)(('GetCommandLineW', windll.kernel32)) # <http://msdn.microsoft.com/en-us/library/bb776391.aspx> CommandLineToArgvW = WINFUNCTYPE(POINTER(LPWSTR), LPCWSTR, POINTER(c_int))( ('CommandLineToArgvW', windll.shell32)) argc = c_int(0) argv_unicode = CommandLineToArgvW(GetCommandLineW(), byref(argc)) argv = [ argv_unicode[i].encode(encoding, 'replace') for i in xrange(0, argc.value)] if not hasattr(sys, 'frozen'): # If this is an executable produced by py2exe or bbfreeze, then it # will have been invoked directly. Otherwise, unicode_argv[0] is the # Python interpreter, so skip that. argv = argv[1:] # Also skip option arguments to the Python interpreter. while len(argv) > 0: arg = argv[0] if not arg.startswith(u'-') or arg == u'-': break argv = argv[1:] if arg == u'-m': # sys.argv[0] should really be the absolute path of the # module source, but never mind. break if arg == u'-c': argv[0] = u'-c' break sys.argv = argv _SYS_ARGV_PROCESSED = True return True