Skip to content

Instantly share code, notes, and snippets.

@mikehearn
Created September 28, 2018 18:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mikehearn/a2f7c9ce5b6d1fc464e9e22aca7e839b to your computer and use it in GitHub Desktop.
Save mikehearn/a2f7c9ce5b6d1fc464e9e22aca7e839b to your computer and use it in GitHub Desktop.
Example of using Kotlin/Native on Windows
typealias WSTR = CPointer<ShortVar>
private fun WSTR.toKString(): String = memScoped {
// Figure out how much memory we need after UTF-8 conversion.
val sz = WideCharToMultiByte(CP_UTF8, WC_ERR_INVALID_CHARS, this@toKString, -1, null, 0, null, null)
// Now convert to UTF-8 and from there, a String.
val utf8 = allocArray<ByteVar>(sz)
val r = WideCharToMultiByte(CP_UTF8, WC_ERR_INVALID_CHARS, this@toKString, -1, utf8, sz, null, null)
if (r == 0) throw RuntimeException("Could not convert to UTF-8")
utf8.toKString()
}
private val fullBinaryPath: String by lazy {
// Get the path to the EXE.
val hmodule = GetModuleHandleW(null)
val wstr: WSTR = nativeHeap.allocArray<ShortVar>(MAX_PATH)
GetModuleFileNameW(hmodule, wstr, MAX_PATH)
// Strip the filename leaving just the directory.
PathRemoveFileSpecW(wstr)
wstr.toKString()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment