Bao Le Duc
02/21/2023, 6:56 AMNSData
to Kotlin ByteArray
?
Background: I’m working on a Kmp library where we need to use OS’s crypto API to encrypt data. So, in Kmp library we define an Interface
interface MessagePackHelper {
fun serialize(payload: String): ByteArray
}
from iOS, we need to implement this interface and set back to the Kmp library. So in Swift, we need to implement below method:
func serialize(payload: String) -> KotlinByteArray {
// let encyrpted = encrypt(payload) // result is NSData obect
// todo - would like to convert NSData -> KotlinByteArray
}
Evegenii Khokhlov
02/21/2023, 7:53 AMfun NSData.toByteArray(): ByteArray {
return ByteArray(length.toInt()).apply {
usePinned {
memcpy(it.addressOf(0), bytes, length)
}
}
}
fun ByteArray.toNSData(): NSData = memScoped {
NSData.create(bytes = allocArrayOf(this@toNSData), length = this@toNSData.size.toULong())
}
Bao Le Duc
02/21/2023, 7:55 AMEvegenii Khokhlov
02/21/2023, 7:55 AMimport platform.Foundation.*
import platform.posix.memcpy
Bao Le Duc
02/21/2023, 7:59 AM