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