初始化C结构数组 - 目标C - OpenGLES

时间:2013-10-17 14:03:13

标签: objective-c c opengl-es struct malloc

我的OpenGL ES应用程序中有以下Vertex结构:

typedef struct Vertex {
float Position[3];
float Color[4];
} Vertex;

在我的标题中,我然后声明:

Vertex *Vertices;

然后在我的init方法中:

 int array = 4;
 Vertices = (Vertex *)malloc(array * sizeof(Vertex));

然后我按如下方式设置网格,其中顶点数组在这种情况下有4个顶点:

- (void)setupMesh {
int count = 0;

for (VerticeObject * object in verticesArray) {

    Vertices[count].Position[0] = object.x;
    Vertices[count].Position[1] = object.y;
    Vertices[count].Position[2] = object.z;

    Vertices[count].Color[0] = 0.9f;
    Vertices[count].Color[1] = 0.9f;
    Vertices[count].Color[2] = 0.9f;
    Vertices[count].Color[3] = 1.0f;

    count ++;
    }
 }

有谁能发现我在这里做错了什么?当我将此Vertices对象传递给OpenGL时,不会绘制任何内容,而如果我将Vertices数组硬编码为:

Vertex Vertices [] = {
{{0.0, 0.0, 0}, {0.9, 0.9, 0.9, 1}},
{{0.0 , 0.0 , 0}, {0.9, 0.9, 0.9, 1}},
{{0.0, 0.0, 0}, {0.9, 0.9, 0.9, 1}},
{{0.0, 0.0, 0}, {0.9, 0.9, 0.9, 1}},
};

一切正常吗?

1 个答案:

答案 0 :(得分:1)

我认为问题在于,在堆栈上分配了一个数组之前,现在你有一个指针(内存地址)到堆上的内存块。所以当你怀疑像sizeof(Vertices)这样的东西时,你的原始sizeof(Vertices)将导致4个顶点,每个顶点保持3个浮点位置和4个浮点颜色 - > 4 *(3 + 4)* 4(float = 4字节)= 112字节。其中sizeof(aPointer) = 4个字节。 OpenGL是一个不容易使用的C库,所以你应该在尝试让它运行之前先了解你的C技能。现在还有一个GLKView课程,这将使所有设置分配更容易。

glBufferData(GL_ARRAY_BUFFER, sizeof(Vertices), Vertices, GL_STATIC_DRAW);

尝试分配与顶点数组相同的大小。在你的情况下4 * sizeof(顶点)。

glBufferData(GL_ARRAY_BUFFER, sizeof(Vertex) * 4, Vertices, GL_STATIC_DRAW);

如果这不起作用,您可以通过将动态分配的数组替换为静态分配来轻松解决问题,因为您在编译时知道它需要多大。

Vertex Vertices[4];

然后像你一样在循环中设置值。