The definition of AudioBuffe开发者_JAVA百科rList looks weird to me… i guess my C is not so good
struct AudioBufferList
{
UInt32 mNumberBuffers;
AudioBuffer mBuffers[kVariableLengthArray];
};
typedef struct AudioBufferList AudioBufferList;
Why
AudioBuffer mBuffers[kVariableLengthArray];
and not
AudioBuffer *mBuffers;
?
kVariableLengthArray appears to be == 1. Eh?
I think i have it working but would appreciate it if anyone could set me straight.
If the symbol kVariableLengthArray
is a compile-time constant, this means that you can allocate a single buffer on the stack ("automatic" storage type, in C).
AudioBufferList single;
single.mNumberBuffers = 1;
Since the struct includes a count, it also means that you can create an instance with any number of buffers, like so:
AudioBufferList * get_n_buffers(size_t num)
{
AudioBufferList *list;
if(num < 1)
return NULL;
list = malloc(sizeof *list + (num - 1) * sizeof list->mBuffers[0]);
list->mNumberBuffers = num;
return list;
}
The latter code dynamically allocates an AudioBufferList
, and relies on the fact that the array is last. So in memory, it will lookas if the AudioBuffer
ends with the proper number of AudioBuffer
instances, as the proper amount of space will be allocated.
AudioBuffer * mBuffers;
You are declaring a pointer to AudioBuffer
In such a case, you need to allocate enough memory, for instance with malloc().
Structures will be placed on the heap, and you will need to free the memory with free() after usage.
AudioBuffer mBuffers[ 1 ];
You are declaring an array of AudioBuffer. Memory is allocated automatically on the stack. No need to call free.
So when it's inside a structure, it's easier to work arrays, as you don't need to allocate memory explicitly to the structure member:
AudioBufferList myBufferList;
Otherwise, you would have to do:
AudioBufferList myBufferList;
myBufferList.mBuffers = malloc( sizeof( AudioBuffer ) * kVariableLengthArray );
/* ... */
free( myBufferList.mBuffers );
精彩评论