forked from sciter-sdk/go-sciter
-
Notifications
You must be signed in to change notification settings - Fork 0
/
utils.go
80 lines (70 loc) · 1.59 KB
/
utils.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
69
70
71
72
73
74
75
76
77
78
79
80
package sciter
/*
#cgo CFLAGS: -Iinclude
#include "sciter-x.h"
*/
import "C"
import (
"syscall"
"unicode/utf16"
"unsafe"
)
// Returns the utf-8 encoding of the utf-16 sequence s,
// with a terminating NUL removed.
func Utf16ToString(s *uint16) string {
if s == nil {
panic("null cstring")
}
us := make([]uint16, 0, 256)
for p := uintptr(unsafe.Pointer(s)); ; p += 2 {
u := *(*uint16)(unsafe.Pointer(p))
if u == 0 {
return string(utf16.Decode(us))
}
us = append(us, u)
}
return ""
}
func Utf16ToStringLength(s *uint16, length int) string {
if s == nil {
panic("null cstring")
}
us := make([]uint16, 0, 256)
for p, i := uintptr(unsafe.Pointer(s)), 0; i < length; p, i = p+2, i+1 {
u := *(*uint16)(unsafe.Pointer(p))
us = append(us, u)
}
return string(utf16.Decode(us))
}
func StringToBytePtr(s string) *byte {
bs := ([]byte)(s)
return &bs[0]
}
func Utf16FromString(s string) ([]uint16, error) {
for i := 0; i < len(s); i++ {
if s[i] == 0 {
return nil, syscall.EINVAL
}
}
return utf16.Encode([]rune(s + "\x00")), nil
}
func StringToWcharPtr(s string) *C.WCHAR {
return (*C.WCHAR)(unsafe.Pointer(StringToUTF16Ptr(s)))
}
func StringToUTF16Ptr(s string) *uint16 {
us, _ := Utf16FromString(s)
return &us[0]
}
func StringToUTF16PtrWithLen(s string) (*uint16, int) {
us, _ := Utf16FromString(s)
length := len(us) - 1
return &us[0], length
}
func ByteCPtrToBytes(bp C.LPCBYTE, size C.UINT) []byte {
bs := C.GoBytes(unsafe.Pointer(bp), C.INT(size))
return bs
}
func BytePtrToBytes(bp *byte, size uint) []byte {
bs := C.GoBytes(unsafe.Pointer(bp), C.INT(size))
return bs
}