为目标 C 静态数组动态分配长度
您好,我对 iOS 编程和使用 Objective C 比较陌生。最近我遇到了一个似乎无法解决的问题,我正在编写一个 OBJ 模型加载器以在我的 iOS 编程中使用。为此,我使用两个数组,如下所示:
static CGFloat modelVertices[360*9]={};
static CGFloat modelColours[360*12]={};
可以看出,当前使用硬编码值 360(特定模型中的面数)分配长度。有没有办法可以从读取 OBJ 文件后计算出的值动态分配该值,如下所示?
int numOfVertices = //whatever this is read from file;
static CGFloat modelColours[numOfVertices*12]={};
我尝试过使用 NSMutable 数组,但发现这些数组很难使用,因为在实际绘制收集的网格时,我需要使用以下代码:
-(void)render
{
// load arrays into the engine
glVertexPointer(vertexStride, GL_FLOAT, 0, vertexes);
glEnableClientState(GL_VERTEX_ARRAY);
glColorPointer(colorStride, GL_FLOAT, 0, colors);
glEnableClientState(GL_COLOR_ARRAY);
//render
glDrawArrays(renderStyle, 0, vertexCount);
}
如您所见,命令 glVertexPointer 需要将值作为 CGFloat 数组:
glVertexPointer (GLint size, GLenum type, GLsizei stride, const GLvoid *pointer);
Hi I am relatively new to programming on iOS and using objective C. Recently I have come across an issue I cannot seem to solve, I am writing a OBJ model loader to use within my iOS programming. For this I use two arrays as below:
static CGFloat modelVertices[360*9]={};
static CGFloat modelColours[360*12]={};
As can be seen the length is currently allocated with a hard coded value of 360 (the number of faces in a particular model). Is there no way this can be dynamically allocated from a value that has been calculated after reading the OBJ file as is done below?
int numOfVertices = //whatever this is read from file;
static CGFloat modelColours[numOfVertices*12]={};
I have tried using NSMutable arrays but found these difficult to use as when it comes to actually drawing the mesh gathered I need to use this code:
-(void)render
{
// load arrays into the engine
glVertexPointer(vertexStride, GL_FLOAT, 0, vertexes);
glEnableClientState(GL_VERTEX_ARRAY);
glColorPointer(colorStride, GL_FLOAT, 0, colors);
glEnableClientState(GL_COLOR_ARRAY);
//render
glDrawArrays(renderStyle, 0, vertexCount);
}
As you can see the command glVertexPointer requires the values as a CGFloat array:
glVertexPointer (GLint size, GLenum type, GLsizei stride, const GLvoid *pointer);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以使用 C 风格的 malloc 为数组动态分配空间。
You could use a c-style malloc to dynamically allocate space for the array.
当声明静态变量时,必须在编译时知道其大小和初始值。您可以做的是将变量声明为指针而不是数组,使用
malloc
或calloc
为数组分配空间并将结果存储在变量中。我在这里使用了
calloc
而不是malloc
,因为静态数组默认会用0填充,这样可以确保代码的一致性。When you declare a static variable, its size and initial value must be known at compile time. What you can do is declare the variable as a pointer instead of an array, the use
malloc
orcalloc
to allocate space for the array and store the result in your variable.I used
calloc
instead ofmalloc
here because a static array would be filled with 0s by default, and this would ensure that the code was consistent.