Skip to content

Instantly share code, notes, and snippets.

@NaniteFactory
Forked from icholy/lpcwstr.go
Last active September 21, 2023 00:12
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save NaniteFactory/9e9d3fe5ea7bfeed788b0795162201c7 to your computer and use it in GitHub Desktop.
Save NaniteFactory/9e9d3fe5ea7bfeed788b0795162201c7 to your computer and use it in GitHub Desktop.
Convert the UTF16 Wide String (WSTR) from/to plain Go string.
package lpcwstr
// #include <windows.h>
// #include <wchar.h>
// #include <WinNT.h>
import "C"
import (
"unicode/utf16"
"unsafe"
)
const maxRunes = 1<<30 - 1
func Decode(cwstr C.LPCWSTR) string {
ptr := unsafe.Pointer(cwstr)
sz := C.wcslen((*C.wchar_t)(ptr))
wstr := (*[maxRunes]uint16)(ptr)[:sz:sz]
return string(utf16.Decode(wstr))
}
func Encode(s string) C.LPCWSTR {
wstr := utf16.Encode([]rune(s))
wstr = append(wstr, 0x00)
return (C.LPCWSTR)(unsafe.Pointer(&wstr[0]))
}
func Encode(s string) C.LPCWSTR {
wstr := utf16.Encode([]rune(s))
p := C.calloc(C.size_t(len(wstr)+1), C.sizeof_uint16_t)
pp := (*[1 << 30]uint16)(p)
copy(pp[:], wstr)
return (C.LPCWSTR)(p)
}
/*On Windows,
syscall.StringToUTF16()
syscall.StringToUTF16Ptr()
syscall.UTF16FromString()
syscall.UTF16PtrFromString()
syscall.UTF16ToString()
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment