我正在尝试在 iOS 中使用一些 Open GL 的东西,但我被 C 的东西困住了,这是我十年来没有使用过的东西。
我用作基础的示例代码声明了 struct Vertex:
typedef struct {
float Position[3];
float Color[4];
} Vertex;
然后,它声明了一个用于数学运算的 C 风格的顶点数组:
Vertex Vertices[] = {
{{0.5, -0.5, 0}, {1, 1, 1, 1}},
{{0.5, 0.5, 0}, {1, 1, 1, 1}},
{{-0.5, 0.5, 0}, {1, 1, 1, 1}},
{{-0.5, -0.5, 0}, {1, 1, 1, 1}}
};
我需要调用一个方法来返回一个新的顶点数组,而不是只使用这个固定数组,这就是我卡住的地方。我想要的是类似的东西(我知道这是完全错误的,它比任何东西都更像伪代码):
- (Vertex (*)[])getLineSegments {
Vertex *vertices = ?? //(need [allPoints count] Vertexs)
for (int i = 0; i < [allPoints count]; i++) {
vertices[i] = { [allPoints[i] getPoints], [allPoints[i] getColor] }; //how do I make a new Vertex in this fashion?
//and then, in getPoints/getColor, how would I make a float[] and return that properly
}
return vertices;
}
只是尝试使用 malloc 实例化和分配值,而我在其他地方读到的东西却惨遭失败:
- (Vertex (*)[])getLineSegments {
Vertex (*vertices)[4] = malloc(sizeof(Vertex) * 4);
Vertex *point = malloc(sizeof(Vertex));
float Pos[3] = {0.5, -0.5, 0}; //error: Array Type Pos[3] is not assingable
point->Position = Pos;
float Color[4] = {1,1,1,1};
point->Color = Color;
vertices[0] = point;
vertices[1] = {{0.5, 0.5, 0} , {1, 1, 1, 1}};
vertices[2] = {{-0.5, 0.5, 0}, {1, 1, 1, 1}};
vertices[3] = {{-0.5, -0.5, 0},{1, 1, 1, 1}}; //errors... errors everywhere
return vertices;
}
我该如何正确地做到这一点?
---
编辑:根据伯顿的建议更新为以下内容。还有一些错误:
- (Vertex (*)[])getLineSegments {
Vertex (*vertices)[4] = malloc(sizeof(Vertex) * 4);
for (int i = 0; i < 4; i++) {
vertices[i] = malloc(sizeof(*vertices[i])); //err: Array type 'Vertex[4]' is not assignable
vertices[i]->Position[0] = 0.5; //this one works. is this correct?
vertices[i].Position[1] = -0.5; //Member reference type 'Vertex *' is a pointer; maybe you meant to use ->?
vertices[i].Position[2] = 0;
vertices[i].Color[0] = 1;
vertices[i].Color[1] = 1;
vertices[i].Color[2] = 1;
vertices[i].Color[3] = 1;
}
return vertices;
}