https://kotlinlang.org logo
#multiplatform
Title
# multiplatform
b

Bao Le Duc

02/21/2023, 6:56 AM
Hi, how can I convert a Swift
NSData
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
Copy code
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:
Copy code
func serialize(payload: String) -> KotlinByteArray {
        // let encyrpted = encrypt(payload) // result is NSData obect
        // todo - would like to convert NSData -> KotlinByteArray
    }
e

Evegenii Khokhlov

02/21/2023, 7:53 AM
Copy code
fun 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()) 
}
b

Bao Le Duc

02/21/2023, 7:55 AM
Thanks @Evegenii Khokhlov. That should be Kotlin code defined in iOS source set, isn’t it?
e

Evegenii Khokhlov

02/21/2023, 7:55 AM
Yes, you are right, you need to
import platform.Foundation.*
and also
import platform.posix.memcpy
b

Bao Le Duc

02/21/2023, 7:59 AM
Great, I will try it out
569 Views