Hi, I'm looking to convert iOS `Data` instance (`i...
# multiplatform
j
Hi, I'm looking to convert iOS
Data
instance (
imageData
below) to Kotlin
ByteArray
in Swift code (so it can be passed to KMP code).....I have following atm but feels like there should be cleaner way to do this?
Copy code
let kotlinByteArray: KotlinByteArray = KotlinByteArray.init(size: Int32(imageData.count))
for (index, element) in imageData.enumerated() {
    kotlinByteArray.set(index: Int32(index), value: Int8(element))
}
h
You can use memcpy that copies the whole content in one step
j
In Swift code?
h
Oh sorry, I missed that part (and I try to avoid Swift code) 😅
r
You could write a Kotlin helper function using memcpy and then call that function from Swift
👍 1
j
Would I not have same issue though in terms of what I'd have to pass from Swift to Kotlin?
r
You can pass the Data straight to Kotlin. It bridges to Obj-C as NSData
(but needs to be in platform-specific source)
j
so, actually, I sort of lied a little above 😃 ....I'm not actually passing data down from Swfit to Kotlin.....rather I'm overriding a Kotlin interface in Swift that has a method that right now returns a ByteArray.....same issue I think but maybe a little less flexibility perhaps
(returns a
KotlinByteArray
in Swift override)
and interface is in commonMain
j
I use this and it works well. You can try it yourself.
Copy code
@OptIn(ExperimentalForeignApi::class)
public fun NSData.toByteArray(): ByteArray {
    return ByteArray(length.toInt()).apply {
        usePinned {
            memcpy(it.addressOf(0), bytes, length)
        }
    }
}
🙏 1
r
You could still add an extra helper fun to do the memcpy and call that from your swift implementation
You ping pong between languages a bit but I don't think it should cause any issue
j
ok, thanks, let me try something like that
r
No idea in practice what the perf difference is so you can decide if it's worth it vs your existing implementation
j
Here is the other way around Kotlin -> Swift.
Copy code
@OptIn(ExperimentalForeignApi::class, BetaInteropApi::class)
public fun ByteArray.toNSData(): NSData = memScoped {
    NSData.create(bytes = allocArrayOf(this@toNSData), length = this@toNSData.size.toULong())
}
j
Actually, the other potential issue here I think is that this is Swift
Data
as opposed to
NSData
.....but can probably convert between them
r
that converts freely when you go from Swift to Obj-C
👍 1
j
that worked, thanks!