如何将Kotlin ByteArray转换为NsData,反之亦然

时间:2019-10-23 10:46:15

标签: kotlin kotlin-multiplatform kotlin-native

与Kotlin Multiplatform项目进行战斗我遇到了一个问题,即需要NsData与我的iOS平台上的sharedModule一起使用Kotlin Native。

因此,我需要将ObjectiveC NsData转换为Kotlin ByteArray并返回。我该怎么办?

1 个答案:

答案 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()) 
}