Francisco Durdin Garcia
Francisco Durdin Garcia

Reputation: 13357

How to convert Kotlin ByteArray to NsData and viceversa

Fighting with a Kotlin Multiplatform project I have ended with the problem of needing to work with NsData on my iOS platform from the sharedModule working with Kotlin Native.

Because of this, I need to transform objectiveC NsData to Kotlin ByteArray and way back. How can I do this?

Upvotes: 23

Views: 7685

Answers (1)

Francisco Durdin Garcia
Francisco Durdin Garcia

Reputation: 13357

NsData to ByteArray

actual typealias ImageBytes = NSData
actual fun ImageBytes.toByteArray(): ByteArray = ByteArray([email protected]()).apply {
    usePinned {
        memcpy(it.addressOf(0), [email protected], [email protected])
    }
}

ByteArray to NsData

actual fun ByteArray.toImageBytes(): ImageBytes? = memScoped {
    val string = NSString.create(string = [email protected]())
    return string.dataUsingEncoding(NSUTF8StringEncoding)
}

ByteArray to NsData different way

actual fun ByteArray.toImageBytes() : ImageBytes = memScoped { 
    NSData.create(bytes = allocArrayOf(this@toImageBytes), 
        length = [email protected]()) 
}

Upvotes: 41

Related Questions