Reputation: 13357
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
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