【问题标题】:How to convert Kotlin ByteArray to NsData and viceversa如何将 Kotlin ByteArray 转换为 NsData,反之亦然
【发布时间】:2020-02-19 14:20:59
【问题描述】:

与 Kotlin 多平台项目的斗争我已经结束了需要在我的 iOS 平台上使用 NsData 的问题,而 sharedModule 使用 Kotlin Native。

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

【问题讨论】:

    标签: kotlin kotlin-multiplatform kotlin-native


    【解决方案1】:

    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@方法
    • 对于查看此解决方案的任何人,请注意需要导入。我发布了gist.github.com/noahsark769/61cfb7a8b7231e2069a9dab94cf74a62,其中包含我在这里使用的完整编译代码
    • 从 KMM 获取 KotlinByteArray 后,如何在 Swift 端将其转换为 nsdata/nsstring?
    • @stackich 我遇到了同样的问题——我发现的唯一方法是在 Kotlin 中定义一个 ByteArray-to-NSData 方法并从 Swift 中调用它。 fun ByteArray.toNSData() = this.usePinned { NSData.create(it.addressOf(0), this.size.convert()) }
    猜你喜欢
    • 2011-07-27
    • 2011-10-08
    • 1970-01-01
    • 2015-01-03
    • 1970-01-01
    • 1970-01-01
    • 2022-01-09
    • 2021-06-10
    • 2012-03-24
    相关资源
    最近更新 更多