与Kotlin Multiplatform项目进行战斗我遇到了一个问题,即需要NsData
与我的iOS平台上的sharedModule
一起使用Kotlin Native。
因此,我需要将ObjectiveC NsData
转换为Kotlin ByteArray
并返回。我该怎么办?
答案 0 :(得分:2)
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)
}
从ByteArray到NsData的不同方式
actual fun ByteArray.toImageBytes() : ImageBytes = memScoped {
NSData.create(bytes = allocArrayOf(this@toImageBytes),
length = this@toImageBytes.size.toULong())
}