【问题标题】:How to access in Swift a C struct that contains a variable sized array?如何在 Swift 中访问包含可变大小数组的 C 结构?
【发布时间】:2019-01-09 01:17:02
【问题描述】:

我有一个项目,目前有一个 C 结构,它被定义为:

typedef struct IDList {

    uint32_t   listID;
    uint32_t   count;
    uint32_t   idArray[];

} __attribute__((packed, aligned(4))) IDList, *IDListPtr;

Objective-C 类中有一个方法可以返回一个 IDListPtr 给我。

我知道我可以:

let idListPtr = theIDManager.getIDList()    // ObjC class that returns the struct

let idList = idListPtr.pointee    // Get the IDList struct from the pointer

而且我知道结构的数组中有 idList.count 项,但是如何在 Swift 中访问该数组?

【问题讨论】:

  • 其他帖子的问题是我无法在 Swift 中访问 idListPtr.pointee.idArray,它只允许我访问 idListPtr.pointee.listIDidListPtr.pointee.count。所以我不知道如何应用该解决方案。

标签: arrays swift struct


【解决方案1】:

C 中的零长度数组在 Swift 中不可见。一种可能的解决方法是在桥接头文件中添加一个帮助函数,该函数返回第一个数组项的地址:

static uint32_t * _Nonnull idArrayPtr(const IDListPtr _Nonnull ptr) { return &ptr->idArray[0]; }

现在你可以在 Swift 中创建一个引用可变长度数组的“缓冲区指针”:

let idListPtr = getIDList()
let idArray = UnsafeBufferPointer(start: idArrayPtr(idListPtr), count: Int(idListPtr.pointee.count))
for item in idArray {
    print(item)
}

【讨论】:

    猜你喜欢
    • 2011-08-19
    • 1970-01-01
    • 2014-03-14
    • 1970-01-01
    • 1970-01-01
    • 2012-04-23
    • 1970-01-01
    • 2020-12-16
    相关资源
    最近更新 更多