如何将字节从 Swift (iOS) 传递到 Kotlin 通用模块?

Sve*_*ven 4 android ios kotlin swift kotlin-multiplatform

为了在 android 和 iOS 应用程序之间共享协议的实现,我正在尝试使用 Kotlin Multiplatform。我按照此处的说明设置了一个基本的多平台项目。

它定义了共享模块中的公共代码......

fun createApplicationScreenMessage() : String {
  return "Kotlin Rocks on ${platformName()}"
}
Run Code Online (Sandbox Code Playgroud)

... 可用于 iOS 项目 CommonKt.createApplicationScreenMessage()

现在想在common模块做IO操作。我为此找到了Kotlinx-io,并且可以在 common 模块中使用它。

但是如何正确设计 kotlin 代码和 swift 代码之间的 api,以便我可以将 InputStream/ByteArray/ByteReadPacket 等价物从 Swift 传递到 kotlin 模块?

例如像 ByteReadPacket 这样的 kotlinx-io 类型:

Kotlin 通用模块:

class ProtocolReader{
    public fun parse(packet: ByteArray): ParsedMessage {
    //parse data
    } 
}
Run Code Online (Sandbox Code Playgroud)

Swift iOS 应用程序

var byteArray = [UInt8](characteristicData)
let reader = ProtocolReader()
reader.parse(byteArray)
Run Code Online (Sandbox Code Playgroud)

这个例子不起作用,因为 swift byteArray 不能与 KotlinByteArray 互操作。

我如何实现这一目标?我是否需要为每个平台定义 api 端点,例如在 Kotlin 多平台项目的 ios 模块中?或者是否有帮助方法从 ios 数据类型创建 kotlinx-io 数据类型?

小智 10

您传递给公共代码的所有内容都需要与平台无关,因此您要么使用期望/实际机制定义模型,要么将 swift 数据类型映射到 kotlin 数据类型。

我不精通swift,但你可以做这样的事情:

let swiftByteArray : [UInt8] = []
let intArray : [Int8] = swiftByteArray
    .map { Int8(bitPattern: $0) }
let kotlinByteArray: KotlinByteArray = KotlinByteArray.init(size: Int32(swiftByteArray.count))
for (index, element) in intArray.enumerated() {
    kotlinByteArray.set(index: Int32(index), value: element)
}
Run Code Online (Sandbox Code Playgroud)

查看生成的互操作性标头有时也有帮助。

科特林字节:

__attribute__((objc_runtime_name("KotlinByte")))
__attribute__((swift_name("KotlinByte")))
@interface MainByte : MainNumber
- (instancetype)initWithChar:(char)value;
+ (instancetype)numberWithChar:(char)value;
@end;
Run Code Online (Sandbox Code Playgroud)

KotlinByteArray:

__attribute__((objc_subclassing_restricted))
__attribute__((swift_name("KotlinByteArray")))
@interface MainKotlinByteArray : KotlinBase
+ (instancetype)arrayWithSize:(int32_t)size 
__attribute__((swift_name("init(size:)")));
+ (instancetype)arrayWithSize:(int32_t)size init:(MainByte *(^)(MainInt *))init 
__attribute__((swift_name("init(size:init:)")));
+ (instancetype)alloc __attribute__((unavailable));
+ (instancetype)allocWithZone:(struct _NSZone *)zone. __attribute__((unavailable));
- (int8_t)getIndex:(int32_t)index __attribute__((swift_name("get(index:)")));
- (MainKotlinByteIterator *)iterator __attribute__((swift_name("iterator()")));
- (void)setIndex:(int32_t)index value:(int8_t)value 
__attribute__((swift_name("set(index:value:)")));
@property (readonly) int32_t size;
@end;
Run Code Online (Sandbox Code Playgroud)