快速访问可变长度数组

标签 swift

Core Audio 有一个 C API,可以将一些数据复制到您提供的内存中。在一种情况下,我需要传入一个指向 AudioBufferList 的指针,它定义为:

struct AudioBufferList {
    var mNumberBuffers: UInt32
    var mBuffers: (AudioBuffer) // this is a variable length array of mNumberBuffers elements
}

UInt32 标识缓冲区的数量,紧随其后的是实际缓冲区。

我可以成功得到这个:

let bufferList = UnsafeMutablePointer<AudioBufferList>.alloc(Int(propsize));
AudioObjectGetPropertyData(self.audioDeviceID, &address, 0, nil, &propsize, bufferList);

我不认识 (AudioBuffer) 语法,但我认为它不重要 - 我认为括号被忽略,mBuffers 只是一个 AudioBuffer,我需要做指针数学来找到第二个。

我试过这个:

let buffer = UnsafeMutablePointer<AudioBuffer>(&bufferList.memory.mBuffers);
// and index via buffer += index;
// Cannot invoke 'init' with an argument of type 'inout (AudioBuffer)'

还试过:

let buffer = UnsafeMutablePointer<Array<AudioBuffer>>(&bufferList.memory.mBuffers);
// and index via buffer[index];
// error: Cannot invoke 'init' with an argument of type '@lvalue (AudioBuffer)'

更笼统的措辞:在 Swift 中,我如何将 UnsafeMutablePointer 带到一个结构并将其视为这些结构的数组?

最佳答案

您可以创建一个从给定地址开始并具有给定 元素数量:

let buffers = UnsafeBufferPointer<AudioBuffer>(start: &bufferList.memory.mBuffers,
    count: Int(bufferList.memory.mNumberBuffers))

for buf in buffers {
    // ...
}

Swift 3(及更高版本)的更新:

let buffers = UnsafeBufferPointer<AudioBuffer>(start: &bufferList.pointee.mBuffers,
    count: Int(bufferList.pointee.mNumberBuffers))

for buf in buffers {
    // ...
}

关于快速访问可变长度数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27061028/

相关文章:

facebook - 在 Swift 中使 UIView 成为一个圆圈

swift - 如何使用 SwiftUI 制作单选列表

ios - 链接来自不同 swift 文件的变量的正确方法是什么?

ios - 无法将行插入 UITableView - Swift 3

ios - 如何强制 UIView 更新

ios - 当我以编程方式进行 segue 时,UIBarButtonItem 不会显示

ios - SnapKit 自动布局损坏 : "Unable to simultaneously satisfy constraints"

ios - 是否可以为 CNContactViewController 添加自定义导航栏?

swift - swift中一个字符串变量占用的内存

ios - 查找给定数据集的局部最大值点