Android 如何将字节从Swift(iOS)传递到Kotlin公共模块?
为了在android和iOS应用程序之间共享协议的实现,我正在使用Kotlin Multiplatform进行试验。我建立了一个基本的多平台项目 它定义了共享模块中的公共代码Android 如何将字节从Swift(iOS)传递到Kotlin公共模块?,android,ios,swift,kotlin,kotlin-multiplatform,Android,Ios,Swift,Kotlin,Kotlin Multiplatform,为了在android和iOS应用程序之间共享协议的实现,我正在使用Kotlin Multiplatform进行试验。我建立了一个基本的多平台项目 它定义了共享模块中的公共代码 fun createApplicationScreenMessage() : String { return "Kotlin Rocks on ${platformName()}" } 。。。可在iOS项目中使用的CommonKt.createApplicationScreenMessage() 现在我想在公共模块中
fun createApplicationScreenMessage() : String {
return "Kotlin Rocks on ${platformName()}"
}
。。。可在iOS项目中使用的CommonKt.createApplicationScreenMessage()
现在我想在公共模块中执行IO操作。我找到了它,可以在公共模块中使用它
但是,如何正确地设计kotlin代码和swift代码之间的api,以便将InputStream/ByteArray/ByteReadPacket等同物从swift传递到kotlin模块
e、 g.类似于kotlinx io类型的东西,如ByteReadPacket:
Kotlin通用模块:
class ProtocolReader{
public fun parse(packet: ByteArray): ParsedMessage {
//parse data
}
}
Swift iOS应用程序
var byteArray = [UInt8](characteristicData)
let reader = ProtocolReader()
reader.parse(byteArray)
此示例不起作用,因为swift byteArray与KotlinByteArray不可互操作
我如何做到这一点?我是否需要为每个平台定义api端点,例如在本例中,在Kotlin多平台项目的ios模块中?或者,是否存在从ios数据类型创建kotlinx io数据类型的辅助方法?传递到通用代码的所有内容都需要与平台无关,因此您可以使用定义模型,或者将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)
}
查看生成的互操作性头有时也会有所帮助
科特林贝特:
__attribute__((objc_runtime_name("KotlinByte")))
__attribute__((swift_name("KotlinByte")))
@interface MainByte : MainNumber
- (instancetype)initWithChar:(char)value;
+ (instancetype)numberWithChar:(char)value;
@end;
KotlinByte阵列:
__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;