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