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

标签 android ios swift kotlin kotlin-multiplatform

为了在 Android 和 iOS 应用程序之间共享协议(protocol)的实现,我正在尝试使用 Kotlin Multiplatform。我按照描述设置了一个基本的多平台项目 here .

它定义共享模块中的公共(public)代码...

fun createApplicationScreenMessage() : String {
  return "Kotlin Rocks on ${platformName()}"
}

... 可以在 iOS 项目中使用 CommonKt.createApplicationScreenMessage()

现在想在common模块中做IO操作。我找到了 Kotlinx-io为此,可以在公共(public)模块中使用它。

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

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

Kotlin 公共(public)模块:

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 数据类型?

最佳答案

您传递给通用代​​码的所有内容都需要与平台无关,因此您要么使用 expect/actual mechanism 定义模型或者您将 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)
}

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

Kotlin 字节:

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

Kotlin 字节数组:

__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;

关于android - 如何将字节从 Swift (iOS) 传递到 Kotlin 通用模块?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55518898/

相关文章:

c - os x swift 构建包管理器无法从 unixODBC C 依赖项中找到共享库

ios - 直接从 textField 移动到 textField 时 UITableView 不会移动

ios - 单击后 UITableViewCell 调整大小,约束发生变化

android - Firebase 身份验证获取移动应用用户

java - JSONObject 和 JSONArray 的区别

android - 从android中的SD卡获取歌曲路径

ios - 单击列表项时获取列表中的缩略图和全尺寸图像

IOS-FB分享打开safari对话框登录

c++ - 使用#define 替换代码

android - 如何在 Android 中构建没有 JNI 的共享库?