How can I convert a C string that isn't zero termi...
# kotlin-native
b
How can I convert a C string that isn't zero terminated? The function
CPointer<ByteVar>.toKString(): String
only work with zero terminated C strings
r
The very definition of a C string is an array of characters terminated by the null character
Wait how can you work with strings not terminated by null, how do you know where they end? Maybe they all have a fixed size?
b
Because those are C bindings for Rust code, and in Rust strings aren't null terminated. I'm given a struct with the string content and a length, so I ended up looping on the content (which is a CPointer<ByteVar>) until length value, and for each iteration I call
content.get(i).toInt().toChar()
to get the next char and append it to my StringBuilder
r
Well that works but it’s quite heavy. I would create a Kotlin
ByteArray
of the right size, fill it in one operation and then just
String(myByteArray)
Can’t you just do
readBytes(count: Int)
on a
CPointer
? Or maybe it’s on a
COpaquePointer
But
COpaquePointer
is
CPointer<out CPointed>
and
ByteVar
extends
CPointed
so you can just do
String((ptr as COpaquePointer).readBytes(count))
or something like that
b
readBytes
work and give me a ByteArray, but I can't do
String(myByteArray)
, I get an error
Using 'String(CharArray): String' is an error. Use CharArray.concatToString() instead
, does I need to convert the ByteArray into a CharArray first?
r
I didn’t know about CharArray, maybe
String(ByteArray)
only works on the JVM. Try
myByteArray.stringFromUtf8()
b
I get unresolved reference for
stringFromUtf8
, but either
decodeToString
or
toKString
seems to works
Copy code
val str: CValue<CRustStrView> = Get_version()
    str.useContents {
        val length: Int = len.toInt()
        val test: ByteArray? = data?.readBytes(length)
        println("Received string : '${test?.toKString()}'")
    }
Thank you !
r
Oh, there is
toKString()
on Kotlin’s
ByteArray
too. Nice
The way to do that changed like 5 times since Kotlin/Native is a thing
n
The String (CPointer<ByteVar>) would need to be terminated by some sort of Character, otherwise there would be no way to know where the String ends.