Hi :wave: , I have a kotlin function (in a KMP mod...
# touchlab-tools
f
Hi 👋 , I have a kotlin function (in a KMP module with SKIE plugin applied) that has this signature:
Copy code
suspend fun onDataReceived(data: ByteArray)
that is translated to this swift signature
Copy code
func onDataReceived(data: Skie.Stdlib.ByteArray.__Kotlin) async throws
How should I convert a swift
[UInt8]
to a
Skie.Stdlib.ByteArray
? Thanks
f
Hi! The
Skie.Stdlib.ByteArray.__Kotlin
is just a typealias to the Kotlin ByteArray, so the conversion works the same as without SKIE.
f
Ok thanks. Will try again with your input.
Posting here a link to some code that converts from Swift's Data to Kotlin's ByteArray (KotlinByteArray) if anyone encounters the same problem I had: https://stackoverflow.com/a/72865245/14999651
d
Here's another option: Use this extension in Swift to convert
[UInt8]
to `Data`:
Copy code
extension Array where Element == UInt8 {
    var data: Data {
        return Data(self)
    }
}
Use this Kotlin helper to convert
NSData
to Kotlin `ByteArray`:
Copy code
// Create in file named NSDataExtensions.kt
@OptIn(ExperimentalForeignApi::class)
fun NSData.toByteArray() = ByteArray(length.toInt()).apply {
    usePinned {
        memcpy(it.addressOf(0), bytes, length)
    }
}
Then, in your Swift code, usage is:
Copy code
let bytes: [UInt8] = [2, 1, 3, 5]
let kotlinByteArray = NSDataExtensionsKt.toByteArray(bytes.data)
🙌 1