C言語におけるoffsetofの意味と理解使用例

1698 ワード

VBOを勉強している間に、こんな質問がありました.
頂点データは次のClass構造で格納されます.
class Vertex
{
public:
	glm::vec3 Position;
	glm::vec4 Color;
};

3つの頂点のデータpush_backからVectorへ
std::vector vertices;

Vertex v;
v.Position = glm::vec3(-5.0f, -5.0f, 0.0f);
v.Color = glm::vec4(1, 0, 0, 1);
vertices.push_back( v);

v.Position = glm::vec3(5.0f, -5.0f, 0.0f);
v.Color = glm::vec4(0, 1, 0, 1);
vertices.push_back( v);

v.Position = glm::vec3(0.0f, 5.0f, 0.0f);
v.Color = glm::vec4(0, 0, 1, 1);
vertices.push_back( v);

VBOを作成して、上の頂点プロパティデータを保存します.
glBindBuffer(GL_ARRAY_BUFFER, m_VboIds[0]);
glBufferData(GL_ARRAY_BUFFER, vertices.size() * sizeof(Vertex), &vertices[0], GL_STATIC_DRAW);

頂点配列ポインタを渡すときに疑問があります.Positionは0なので、Color属性データに対してオフセットを計算します.
この時はoffsetofで手伝うことができます.
glBindBuffer(GL_ARRAY_BUFFER, m_VboIds[0]);
glVertexAttribPointer(m_program.m_position, 3, GL_FLOAT, false, sizeof(Vertex),(GLvoid*)0);
glVertexAttribPointer(m_program.m_color, 4, GL_FLOAT, false, sizeof(Vertex), (GLvoid*)offsetof(Vertex,Vertex::Color));

offsetofはstddefでマクロです.hで定義
#define offsetof(struct_t,member) ((size_t)(char *)&((struct_t *)0)->member)

転入先http://blog.csdn.net/huutu http://www.thisisgame.com.cn
offsetofの説明:
(struct_t *)0     struct_t     ,      0,            0              struct_t      。

((struct_t *)0)->member           member,    &((struct_t *)0)->member)            。

           0,                           。         ,    size_t   (size_t        )。

  ,offsetoff(struct_t,member)          member   struct_t     。