【发布时间】:2020-02-19 14:20:59
【问题描述】:
与 Kotlin 多平台项目的斗争我已经结束了需要在我的 iOS 平台上使用 NsData 的问题,而 sharedModule 使用 Kotlin Native。
因此,我需要将objectiveC NsData 转换为Kotlin ByteArray 并返回。我该怎么做?
【问题讨论】:
标签: kotlin kotlin-multiplatform kotlin-native
与 Kotlin 多平台项目的斗争我已经结束了需要在我的 iOS 平台上使用 NsData 的问题,而 sharedModule 使用 Kotlin Native。
因此,我需要将objectiveC NsData 转换为Kotlin ByteArray 并返回。我该怎么做?
【问题讨论】:
标签: kotlin kotlin-multiplatform kotlin-native
NsData 转字节数组
actual typealias ImageBytes = NSData
actual fun ImageBytes.toByteArray(): ByteArray = ByteArray(this@toByteArray.length.toInt()).apply {
usePinned {
memcpy(it.addressOf(0), this@toByteArray.bytes, this@toByteArray.length)
}
}
ByteArray 到 NsData
actual fun ByteArray.toImageBytes(): ImageBytes? = memScoped {
val string = NSString.create(string = this@toImageBytes.decodeToString())
return string.dataUsingEncoding(NSUTF8StringEncoding)
}
ByteArray 到 NsData 的不同方式
actual fun ByteArray.toImageBytes() : ImageBytes = memScoped {
NSData.create(bytes = allocArrayOf(this@toImageBytes),
length = this@toImageBytes.size.toULong())
}
【讨论】:
NSString 可能会给你一个搞砸的结果,因为这种转换会增加额外的字节到输出,这就是为什么最好使用 only @ 987654326@方法
ByteArray-to-NSData 方法并从 Swift 中调用它。 fun ByteArray.toNSData() = this.usePinned { NSData.create(it.addressOf(0), this.size.convert()) }