You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

构建KMM多平台库:处理Swift特定类与跨平台数据兼容

实现KMM库跨平台数据统一处理方案

下面是针对你的需求的具体实现方案,涵盖字节数据桥接、集合通用处理以及构造函数的平台适配:

1. 核心思路

通过KMM的**预期(expect)/实际(actual)**机制隔离平台差异,将核心业务逻辑(字节遍历、集合处理)放在通用代码中复用,仅在iOS端做UnsafeRawBufferPointer到ByteArray的转换适配。


2. 完整代码实现

通用代码(commonMain)

所有跨平台复用的逻辑和类声明都放在这里:

// 跨平台类的预期声明,定义通用构造函数和方法
expect class DataProcessor(
    byteData: ByteArray,
    itemList: List<String>,
    dataMap: Map<String, Int>
) {
    fun process(): String
}

// 通用字节遍历逻辑,所有平台共用
fun ByteArray.processBytes(): String {
    val result = StringBuilder()
    for (byte in this) {
        // 替换为你的逐字节业务逻辑,比如转十六进制、校验等
        result.append(String.format("%02X ", byte))
    }
    return result.toString().trim()
}

iOS平台适配代码(iosMain)

仅处理iOS端的UnsafeRawBufferPointer转换,不侵入通用逻辑:

import kotlinx.cinterop.memcpy
import kotlinx.cinterop.refTo
import kotlinx.cinterop.UnsafeRawBufferPointer

actual class DataProcessor actual constructor(
    private val byteData: ByteArray,
    private val itemList: List<String>,
    private val dataMap: Map<String, Int>
) {
    // 供Swift调用的构造函数,直接接收UnsafeRawBufferPointer
    constructor(
        buffer: UnsafeRawBufferPointer,
        itemList: List<String>,
        dataMap: Map<String, Int>
    ) : this(buffer.toByteArray(), itemList, dataMap)

    actual fun process(): String {
        val byteResult = byteData.processBytes()
        val listResult = itemList.joinToString(prefix = "[", postfix = "]")
        val mapResult = dataMap.entries.joinToString(prefix = "{", postfix = "}") { "${it.key}: ${it.value}" }
        return """
            字节处理结果: $byteResult
            列表内容: $listResult
            映射内容: $mapResult
        """.trimIndent()
    }
}

// 扩展方法:将UnsafeRawBufferPointer转为Kotlin ByteArray
private fun UnsafeRawBufferPointer.toByteArray(): ByteArray {
    val byteArray = ByteArray(count)
    if (count > 0) {
        memcpy(byteArray.refTo(0), baseAddress, count.toULong())
    }
    return byteArray
}

Swift端调用示例

直接使用UnsafeRawBufferPointer构造实例,集合类型自动桥接:

import Foundation
import YourKmmLibrary

// 测试数据
let testData = Data([0x10, 0x20, 0x30, 0x40])
let testList = ["First", "Second", "Third"]
let testMap = ["A": 100, "B": 200]

// 用Data的withUnsafeBytes获取UnsafeRawBufferPointer
testData.withUnsafeBytes { buffer in
    let processor = DataProcessor(buffer: buffer, itemList: testList, dataMap: testMap)
    print(processor.process())
}

3. 关键细节说明

  • 集合自动桥接:KMM原生支持Kotlin List/Map与Swift Array/Dictionary的双向转换,通用代码中直接用Kotlin集合类型即可,无需额外适配。
  • 逻辑复用:字节遍历、集合处理等核心逻辑仅在通用代码中写一次,所有平台共享,避免重复开发。
  • 平台隔离:仅在iOS端处理UnsafeRawBufferPointer的转换,不影响其他平台的实现。

内容的提问来源于stack exchange,提问作者Nishain de Silva

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.23 21:20:12