Search code examples
kotlinkotlin-multiplatformkotlin-native

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?


Solution

  • NsData to ByteArray

    actual typealias ImageBytes = NSData
    actual fun ImageBytes.toByteArray(): ByteArray = ByteArray(this@toByteArray.length.toInt()).apply {
        usePinned {
            memcpy(it.addressOf(0), this@toByteArray.bytes, this@toByteArray.length)
        }
    }
    

    ByteArray to NsData

    actual fun ByteArray.toImageBytes(): ImageBytes? = memScoped {
        val string = NSString.create(string = this@toImageBytes.decodeToString())
        return string.dataUsingEncoding(NSUTF8StringEncoding)
    }
    

    ByteArray to NsData different way

    actual fun ByteArray.toImageBytes() : ImageBytes = memScoped { 
        NSData.create(bytes = allocArrayOf(this@toImageBytes), 
            length = this@toImageBytes.size.toULong()) 
    }