在使用 Kotlin Multiplatform 项目时,我遇到了一个问题:需要从 Kotlin Native 的 sharedModule
平台使用 NsData
来与 iOS 平台进行交互。
因此,我需要将 Objective-C 的 NsData
转换为 Kotlin 的 ByteArray
,并且反过来也需要转换。如何实现这个功能呢?
在使用 Kotlin Multiplatform 项目时,我遇到了一个问题:需要从 Kotlin Native 的 sharedModule
平台使用 NsData
来与 iOS 平台进行交互。
因此,我需要将 Objective-C 的 NsData
转换为 Kotlin 的 ByteArray
,并且反过来也需要转换。如何实现这个功能呢?
NsData 转 ByteArray
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)
}
将字节数组转换为NsData的另一种方式
actual fun ByteArray.toImageBytes() : ImageBytes = memScoped {
NSData.create(bytes = allocArrayOf(this@toImageBytes),
length = this@toImageBytes.size.toULong())
}
NSString
转换为其他类型再转回来的选项可能会导致结果混乱,因为这种转换会向输出添加额外的字节,因此最好仅使用allocArrayOf
方法。 - schmidt9fun ByteArray.toNSData() = this.usePinned { NSData.create(it.addressOf(0), this.size.convert()) }
- Nolan Amy