Core Audio has a C API that copies some data into memory you supply. In one case, I need to pass in a pointer to an AudioBufferList, which is defined as:
struct AudioBufferList {
var mNumberBuffers: UInt32
var mBuffers: (AudioBuffer) // this is a variable length array of mNumberBuffers elements
}
The UInt32 identifies the number of buffers, and the actual buffers immediately follow.
I can get this successfully:
let bufferList = UnsafeMutablePointer<AudioBufferList>.alloc(Int(propsize));
AudioObjectGetPropertyData(self.audioDeviceID, &address, 0, nil, &propsize, bufferList);
I don't recognize the (AudioBuffer) syntax but I don't think it's significant - I think the brackets are ignored and mBuffers is just an AudioBuffer and it's up to me to do the pointer math to find the second one.
I tried this:
let buffer = UnsafeMutablePointer<AudioBuffer>(&bufferList.memory.mBuffers);
// and index via buffer += index;
// Cannot invoke 'init' with an argument of type 'inout (AudioBuffer)'
Also tried:
let buffer = UnsafeMutablePointer<Array<AudioBuffer>>(&bufferList.memory.mBuffers);
// and index via buffer[index];
// error: Cannot invoke 'init' with an argument of type '@lvalue (AudioBuffer)'
Phrased more generically: In Swift, how can I take an UnsafeMutablePointer to a structure and treat it as an array of those structures?
You can create a buffer pointer that starts at the given address and has the given number of elements:
let buffers = UnsafeBufferPointer<AudioBuffer>(start: &bufferList.memory.mBuffers,
count: Int(bufferList.memory.mNumberBuffers))
for buf in buffers {
// ...
}
Update for Swift 3 (and later):
let buffers = UnsafeBufferPointer<AudioBuffer>(start: &bufferList.pointee.mBuffers,
count: Int(bufferList.pointee.mNumberBuffers))
for buf in buffers {
// ...
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With