Swift访问可变长度数组

时间:2014-11-21 12:06:16

标签: 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作为结构并将其视为这些结构的数组?

1 个答案:

答案 0 :(得分:9)

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

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