Can I avoid using offsetof in the following?

夙愿已清 提交于 2019-12-25 10:02:53

问题


Following another question from me, here is a specific example where I want to avoid offsetof.

For using with glVertexAttribPointer, I have to use offsetof for the last parameter.

 glVertexAttribPointer(GLKVertexAttribColor, 4, GL_FLOAT, GL_FALSE, sizeof(Vertex),
            (const GLvoid *) offsetof(Vertex, _color));

Vertex is a class. Is there a way I can avoid using this one? I tried with pointer to members, but no luck.

Cannot compile in the following

glVertexAttribPointer(GLKVertexAttribColor, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex),
        (const GLvoid *)&Vertex::_color);

回答1:


You cannot get the address of a non-static member qualified as Vertex::_color. You would need an instance of Vertex, but even then the address returned would be relative to the program's address space and this is not what you want when you use VBOs.

offsetof (...) is used is to find the address of an element in a data structure. This address does not point to actual memory, it is literally just an offset from the beginning of the structure (and this is why it uses size_t rather than intptr_t or void *).

Historically, when vertex arrays were introduced in OpenGL 1.1, it used the data pointer in a call to glVertexPointer (...) to reference client (program) memory. Back then, the address you passed actually pointed to memory in your program. Beginning with Vertex Buffer Objects (GL 1.5), OpenGL re-purposed the pointer parameter in glVertexPointer (...) to serve as a pointer to server (GPU) memory. If you have a non-zero VBO bound when you call glVertexPointer (...) then the pointer is actually an offset.

More precisely, the pointer when using VBOs is relative to the bound VBO's data store and the first datum in your VBO begins at address 0. This is why offsetof (...) makes sense in this context, and there is no reason to avoid using it.



来源:https://stackoverflow.com/questions/22726351/can-i-avoid-using-offsetof-in-the-following

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!