From dfac13a7a7685ab670107ac320b2c0c27dac6942 Mon Sep 17 00:00:00 2001 From: igotti-google Date: Sat, 30 Jun 2018 19:45:11 +0300 Subject: [PATCH] Add toKString() from short array --- .../src/main/kotlin/kotlinx/cinterop/Utils.kt | 1 + .../native/kotlin/kotlinx/cinterop/NativeMem.kt | 17 +++++++++++++++++ 2 files changed, 18 insertions(+) diff --git a/Interop/Runtime/src/main/kotlin/kotlinx/cinterop/Utils.kt b/Interop/Runtime/src/main/kotlin/kotlinx/cinterop/Utils.kt index 14a9b87e9cc..2a9ff2b2b0d 100644 --- a/Interop/Runtime/src/main/kotlin/kotlinx/cinterop/Utils.kt +++ b/Interop/Runtime/src/main/kotlin/kotlinx/cinterop/Utils.kt @@ -395,6 +395,7 @@ val String.wcstr: CValues * * @return the [kotlin.String] decoded from given zero-terminated UTF-8-encoded C string. */ +// TODO: optimize fun CPointer.toKString(): String { val nativeBytes = this diff --git a/Interop/Runtime/src/native/kotlin/kotlinx/cinterop/NativeMem.kt b/Interop/Runtime/src/native/kotlin/kotlinx/cinterop/NativeMem.kt index 4d9b25c1789..ef2a725d2a8 100644 --- a/Interop/Runtime/src/native/kotlin/kotlinx/cinterop/NativeMem.kt +++ b/Interop/Runtime/src/native/kotlin/kotlinx/cinterop/NativeMem.kt @@ -112,6 +112,23 @@ internal object nativeMemUtils { } } +fun CPointer.toKString(): String { + val nativeBytes = this + + var length = 0 + while (nativeBytes[length] != 0.toShort()) { + ++length + } + val bytes = CharArray(length) + var index = 0 + while (index < length) { + bytes[index] = nativeBytes[index].toChar() + ++index + } + return String(bytes) +} + + @SymbolName("Kotlin_interop_malloc") private external fun malloc(size: Long, align: Int): NativePtr