Kotlin Native 如何将 ByteArray 转换为 String?

Kotlin Native how to convert ByteArray to String?

我在玩kotlin-native samples。 我想知道如何从 pinned ByteArray 中获取 String。只想在控制台打印出来。

如果您需要 JVM 的解决方案,因为 stringFromUtf8 仅适用于本机平台,请使用 toString with a Charset 作为参数:

val byteArray = "Hello World".toByteArray(Charsets.UTF_8)   
val str = byteArray.toString(Charsets.UTF_8)

如果您特别只想定位到原生,请使用

这个API好像变了

现在只需使用这个:string.toUtf8(start, end)

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

旧版:

使用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)

参见here

如果byteArray通过互操作C APIs类似于CPointer<ByteVar>,请在Kotlin-Native

中使用.toKString()