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/