Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift access to variable length array

Tags:

swift

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?

like image 474
stevex Avatar asked Nov 21 '14 12:11

stevex


1 Answers

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 {
    // ...
}
like image 128
Martin R Avatar answered Sep 29 '22 08:09

Martin R