Can I avoid using offsetof in the following?

2019-08-16 09:06发布

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条回答
【Aperson】
2楼-- · 2019-08-16 09:17

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.

查看更多
登录 后发表回答