Search code examples
kotlinkotlin-interopkotlin-native

Kotlin Native how to convert ByteArray to String?


I was playing with the kotlin-native samples. I wonder how I could get String from pinned ByteArray. Just want to print it in the console.


Solution

  • It seems that this API has changed

    Now just use this: string.toUtf8(start, end)

    https://github.com/JetBrains/kotlin-native/commit/cba7319e982ed9ba2dceb517a481cb54ed1b9352#diff-45a5f8d37067266e27b76d1b68f01173

    Legacy version:

    Use stringFromUtf8

    /**
     * Converts an UTF-8 array into a [String]. Replaces invalid input sequences with a default character.
     */
    fun ByteArray.stringFromUtf8(start: Int = 0, size: Int = this.size) : String =
            stringFromUtf8Impl(start, size)
    

    See here.

    And if the byteArray is like CPointer<ByteVar> by interoperating C APIs, pleace use .toKString() in Kotlin-Native