From f945509739602000305fa4fe4b35ce26c9474fa2 Mon Sep 17 00:00:00 2001 From: MURAOKA Taro Date: Thu, 13 Jul 2023 00:57:00 +0900 Subject: [PATCH] Specialize the conversion between wchar_t* and Go string on Windows only. --- wchar.go | 2 ++ wchar_windows.go | 27 +++++++++++++++++++++++++++ 2 files changed, 29 insertions(+) create mode 100644 wchar_windows.go diff --git a/wchar.go b/wchar.go index 8ec3566..9c4c870 100644 --- a/wchar.go +++ b/wchar.go @@ -21,6 +21,8 @@ // OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF // SUCH DAMAGE. +//go:build !windows + package hid /* diff --git a/wchar_windows.go b/wchar_windows.go new file mode 100644 index 0000000..701de37 --- /dev/null +++ b/wchar_windows.go @@ -0,0 +1,27 @@ +package hid + +/* +#include +*/ +import "C" + +import ( + "golang.org/x/sys/windows" +) + +// gotowcs converts a Go string to a C wide string. The returned string must +// be freed by the caller by calling C.free. +func gotowcs(s string) *C.wchar_t { + u16s, err := windows.UTF16FromString(s) + if err != nil { + panic(err) + } + n := C.size_t(len(u16s)) + wcs := (*C.wchar_t)(calloc(n+1, C.sizeof_wchar_t)) + return C.wmemcpy(wcs, (*C.wchar_t)(&u16s[0]), n) +} + +// wcstogo converts a C wide string to a Go string. +func wcstogo(wcs *C.wchar_t) string { + return windows.UTF16PtrToString((*uint16)(wcs)) +}