-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwcstring.go
48 lines (40 loc) · 1.03 KB
/
wcstring.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
// +build windows
package lexfloatclient
import "C"
import (
"bytes"
"encoding/binary"
"unicode/utf16"
"unsafe"
)
const (
maxCArrayLength C.uint = 4096
maxGoArrayLength C.int = 4096
)
func goToCString(goString string) *C.ushort {
bytes := []rune(goString)
encodedBytes := utf16.Encode(bytes)
// Ensure the slice is null-terminated
encodedBytes = append(encodedBytes, 0)
cString := (*C.ushort)(unsafe.Pointer(&encodedBytes[0]))
return cString
}
func ctoGoString(cString *C.ushort) string {
encodedBytes := C.GoBytes(unsafe.Pointer(cString), maxGoArrayLength)
goString, _ := decodeUtf16(encodedBytes, binary.LittleEndian)
return goString
}
func getCArray() [maxCArrayLength]C.ushort {
var cArray [maxCArrayLength]C.ushort
return cArray
}
func freeCString(cString *C.ushort) {
// do nothing
}
func decodeUtf16(b []byte, order binary.ByteOrder) (string, error) {
ints := make([]uint16, len(b)/2)
if err := binary.Read(bytes.NewReader(b), order, &ints); err != nil {
return "", err
}
return string(utf16.Decode(ints)), nil
}