问题
I have an NSMutableArray called mVerticies stored as a member of my class and I'd like to place them into a float array to draw them with glVertexAttribPointer.
Normally when drawing, I would have something like:
float verticies[] = {-1, -1, 1, -1};
// ... prepare to draw
glVertexAttribPointer(GLKVertexAttribPosition,
2, GL_FLOAT, GL_FALSE, 0, verticies);
// ... draw
But in order to use the glVertexAttribPointer function, i need a float[]. The verticies are stored as an NSMutableArray because they change quite often. Is there an easy way to either store a dynamic float[] as a member or to quickly convert an NSMutableArray to a float[]?
回答1:
Assuming the values are stored as NSNumbers, you can do something like this:
float *floatsArray = malloc([numbersArray count] * sizeof(float));
if (floatsArray == NULL) {
// handle error
}
[numbersArray enumerateObjectsWithOptions:NSEnumerationConcurrent usingBlock:^(NSNumber *number, NSUInteger idx, BOOL *stop) {
floatsArray[idx] = [number floatValue];
}];
// use floatsArray
free(floatsArray);
回答2:
You need to use malloc if you just want a raw chunk memory to read and write values directly.
If you have an NSArray array containing NSNumber instances:
float *vertices = malloc(sizeof(float) * [array count]);
for (int i = 0; i < [array count]; i++) {
vertices[i] = [[array objectAtIndex:i] floatValue];
}
// draw cool 3D objects and stuff
glVertexAttribPointer(....)
// then, when you're totally done with the memory
free(vertices);
Unlike Objective-C objects, the vertices pointer doesn't have a retain count, so you need to free it yourself, and keep track of when you can free it, because when you call free it will be gone immediately.
回答3:
Just loop through the values. Assuming your floats are stored as NSNumbers:
NSUInteger count = [mutableVerticesArray count];
float vertices[count];
for (NSUInteger i = 0; i < count; i++) {
vertices[i] = [[mutableVerticesArray objectAtIndex:i] floatValue];
}
// Drawing etc.
来源:https://stackoverflow.com/questions/9285559/copy-nsmutablearray-into-array-of-floats-for-gles-rendering