Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #http://msdn.microsoft.com/en-us/library/windows/desktop/dd374130
- #http://code.google.com/p/pywinauto/source/browse/pywinauto/win32defines.py?r=ab2f9eb3fc0cfb5d2faaa4326ca7d598474a39ca
- from ctypes import *
- from ctypes.wintypes import *
- import sys
- def wide2multibyte(fn):
- """Map a UTF-16 (wide character) string to a new character string. The new
- character string is not necessarily from a multibyte character set.
- Objective: take a unicode string and convert it to a multibyte string that
- Windows can use to represent file names in e.g. Chinese (mbcs will only work
- if the host system 'happens to be' in the right geographical location)."""
- if not sys.platform.startswith("win"):
- return fn
- # constants, taken from pywinauto package
- CP_UTF8 = 65001 # Variable c_int
- CP_ACP = 0 # Variable c_int
- NULL = 0 # Variable c_int
- LPBOOL = POINTER(c_long)
- fnEnc = fn.encode("utf-16-le")
- codePage = CP_UTF8 # --> Ergo: lpDefaultChar, lpUsedDefaultChar must be NULL
- codePage = CP_ACP
- dwFlags = 0
- lpWideCharStr = fnEnc
- cchWideChar = len(fn) # counts the number of chars, not bytes
- lpMultiByteStr = create_string_buffer(len(fnEnc))
- cbMultiByte = 0
- lpDefaultChar = c_char_p(NULL) # ???
- lpUsedDefaultChar = c_int(NULL)
- #Returns the number of bytes written to the buffer pointed to by lpMultiByteStr if successful.
- wideCharToMultiByte = windll.kernel32.WideCharToMultiByte
- wideCharToMultiByte.restype = c_int
- wideCharToMultiByte.argtypes = [UINT, DWORD, LPCWSTR,
- c_int, LPSTR, c_int,
- LPCSTR, LPBOOL]
- # why don't ArgumentErrors have a zero-based origin?
- # E.g. 'ArgumentError: argument 1:...' means 'wrong type for codePage parameter'!
- # determine size
- mbcssize = wideCharToMultiByte(codePage, dwFlags, lpWideCharStr,
- cchWideChar, lpMultiByteStr, cbMultiByte,
- lpDefaultChar, lpUsedDefaultChar)
- # do conversion
- retcode = wideCharToMultiByte(codePage, dwFlags, lpWideCharStr,
- cchWideChar, lpMultiByteStr, mbcssize,
- lpDefaultChar, lpUsedDefaultChar)
- print retcode
- print mbcssize
- print repr(lpMultiByteStr.value), lpMultiByteStr.value
- if mbcssize <= 0:
- getLastError = windll.kernel32.GetLastError
- getLastError.restype = DWORD
- retcodes = {122: "ERROR_INSUFFICIENT_BUFFER",
- 1004: "ERROR_INVALID_FLAGS",
- 87: "ERROR_INVALID_PARAMETER",
- 1113: "ERROR_NO_UNICODE_TRANSLATION"}
- retcode = getLastError()
- print "Error:", retcodes.get(retcode, retcode) # error code: 0
- return lpMultiByteStr.value
- fn = u'\u0c0f\u0c2e\u0c02\u0c21\u0c40' + '.txt'
- wide2multibyte(fn)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement