-
Notifications
You must be signed in to change notification settings - Fork 2
/
main_windows.go
68 lines (62 loc) · 1.63 KB
/
main_windows.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
package mbcs
import (
"unsafe"
"golang.org/x/sys/windows"
)
var kernel32 = windows.NewLazySystemDLL("kernel32")
var multiByteToWideChar = kernel32.NewProc("MultiByteToWideChar")
var wideCharToMultiByte = kernel32.NewProc("WideCharToMultiByte")
var getConsoleCP = kernel32.NewProc("GetConsoleCP")
func ansiToUtf8(mbcs []byte, codepage uintptr) (string, error) {
if mbcs == nil || len(mbcs) <= 0 {
return "", nil
}
size, _, _ := multiByteToWideChar.Call(
codepage, 0,
uintptr(unsafe.Pointer(&mbcs[0])),
uintptr(len(mbcs)),
uintptr(0), 0)
if size <= 0 {
return "", windows.GetLastError()
}
utf16 := make([]uint16, size)
rc, _, _ := multiByteToWideChar.Call(
codepage, 0,
uintptr(unsafe.Pointer(&mbcs[0])), uintptr(len(mbcs)),
uintptr(unsafe.Pointer(&utf16[0])), size)
if rc == 0 {
return "", windows.GetLastError()
}
return windows.UTF16ToString(utf16), nil
}
func utf8ToAnsi(utf8 string, codepage uintptr) ([]byte, error) {
utf16, err := windows.UTF16FromString(utf8)
if err != nil {
return nil, err
}
size, _, _ := wideCharToMultiByte.Call(
codepage, 0,
uintptr(unsafe.Pointer(&utf16[0])),
uintptr(len(utf16)),
uintptr(0), 0, uintptr(0), uintptr(0))
if size <= 0 {
return nil, windows.GetLastError()
}
mbcs := make([]byte, size)
rc, _, _ := wideCharToMultiByte.Call(
codepage, 0,
uintptr(unsafe.Pointer(&utf16[0])),
uintptr(len(utf16)),
uintptr(unsafe.Pointer(&mbcs[0])), size, uintptr(0), uintptr(0))
if rc == 0 {
return nil, windows.GetLastError()
}
if mbcs[size-1] == 0 {
mbcs = mbcs[:size-1]
}
return mbcs, nil
}
func consoleCP() uintptr {
cp, _, _ := getConsoleCP.Call()
return cp
}