Kotlin-native: How to convert NSData to ByteArray?

Created on 10 Jul 2019  路  2Comments  路  Source: JetBrains/kotlin-native

We need to use protobuf(Objective-C GPBMessage) in common code, thus we inherit GPBMessage and delegate it's fields to Kotlin properties. Then we can use wire to wrap these objects.

Now we need convert NSData to ByteArray(infact we need okio/ByteString, which initialed with ByteArray), we do this work like this:

val byteArray = nsData.bytes?.readBytes(nsData.length.toInt())

We also need convert ByteArray to NSData, we do it like this:

byteArray.usePinned {
    origin.imageData = NSData.dataWithBytes(it.addressOf(0), it.get().size.toULong())
}

Is this is the right way?

Most helpful comment

 val d = memScoped {  NSData.create(bytes = "Hello".cstr.ptr, length = 5u) }
 val b = ByteArray(d.length.toInt()).apply {
        usePinned {
                memcpy(it.addressOf(0), d.bytes, d.length)
        }
  }
println(b.stringFromUtf8())

All 2 comments

Looks right to me! Prob a good question for the multiplatform Kotlin slack channel

 val d = memScoped {  NSData.create(bytes = "Hello".cstr.ptr, length = 5u) }
 val b = ByteArray(d.length.toInt()).apply {
        usePinned {
                memcpy(it.addressOf(0), d.bytes, d.length)
        }
  }
println(b.stringFromUtf8())
Was this page helpful?
0 / 5 - 0 ratings

Related issues

alastaircoote picture alastaircoote  路  3Comments

nvlizlo picture nvlizlo  路  4Comments

msink picture msink  路  4Comments

jonnyzzz picture jonnyzzz  路  4Comments

SBNTT picture SBNTT  路  4Comments