Skip to content

Commit

Permalink
Specialize the conversion between wchar_t* and Go string on Windows o…
Browse files Browse the repository at this point in the history
…nly.
  • Loading branch information
koron committed Jul 12, 2023
1 parent b83ecec commit fa9e67a
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 0 deletions.
2 changes: 2 additions & 0 deletions wchar.go
Original file line number Diff line number Diff line change
Expand Up @@ -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

/*
Expand Down
29 changes: 29 additions & 0 deletions wchar_windows.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
package hid

/*
#include <wchar.h>
*/
import "C"

import (
"unsafe"

"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)(unsafe.Pointer(&u16s[0])), n)
}

// wcstogo converts a C wide string to a Go string.
func wcstogo(wcs *C.wchar_t) string {
return windows.UTF16PtrToString((*uint16)(unsafe.Pointer(wcs)))
}

0 comments on commit fa9e67a

Please sign in to comment.