9

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?

1 Answer 1

12

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 {
    // ...
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.