Created
May 18, 2018 05:37
-
-
Save randy3k/b03f1e00277ba6f5c4cafe996f31e21c to your computer and use it in GitHub Desktop.
python ctypes wctomb and mbtowc
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import rapi | |
| rapi.start() | |
| # let R to set the locale | |
| import ctypes | |
| from ctypes import wintypes | |
| 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 | |
| wctomb = ctypes.cdll.msvcrt.wctomb | |
| wctomb.argtypes = [ctypes.POINTER(ctypes.c_char), ctypes.c_wchar] | |
| wctomb.restype = ctypes.c_int | |
| mbtowc = ctypes.cdll.msvcrt.mbtowc | |
| mbtowc.argtypes = [ctypes.POINTER(ctypes.c_wchar), ctypes.POINTER(ctypes.c_char), ctypes.c_size_t] | |
| mbtowc.restype = ctypes.c_int | |
| def utf8tosystem(text): | |
| s = ctypes.create_string_buffer(10) | |
| buf = b"" | |
| for c in text: | |
| n = wctomb(s, c) | |
| if n > 0: | |
| buf += s[:n] | |
| return buf | |
| def system2utf8(buf): | |
| wcbuf = ctypes.create_unicode_buffer(1) | |
| text = "" | |
| while buf: | |
| n = mbtowc(wcbuf, buf, len(p)) | |
| if n <= 0: | |
| break | |
| text += wcbuf[0] | |
| buf = buf[n:] | |
| return text | |
| p = utf8tosystem("甲乙丙") | |
| systemtoutf8(p) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment