一尘不染

快速访问可变长度数组

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带到一个结构并将其视为这些结构的数组?


阅读 328

收藏
2020-07-07

共1个答案

一尘不染

您可以创建一个从给定地址开始并具有给定元素数量的缓冲区指针:

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 {
    // ...
}
2020-07-07