Skip to content

Instantly share code, notes, and snippets.

@justenwalker
Last active July 31, 2020 02:49
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save justenwalker/d2fa7c80e6454bf7d5314ee2f28d1b00 to your computer and use it in GitHub Desktop.
Save justenwalker/d2fa7c80e6454bf7d5314ee2f28d1b00 to your computer and use it in GitHub Desktop.
Convert Go strings to C-compatible strings for Windows API Calls
package win32
import "unicode/utf16"
// StringToCharPtr converts a Go string into pointer to a null-terminated cstring.
// This assumes the go string is already ANSI encoded.
func StringToCharPtr(str string) *uint8 {
chars := append([]byte(str), 0) // null terminated
return &chars[0]
}
// StringToUTF16Ptr converts a Go string into a pointer to a null-terminated UTF-16 wide string.
// This assumes str is of a UTF-8 compatible encoding so that it can be re-encoded as UTF-16.
func StringToUTF16Ptr(str string) *uint16 {
wchars := utf16.Encode([]rune(str + "\x00"))
return &wchars[0]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment