Bojangles - 3 months ago 17

C++ Question

I've written a model loader in C++ an OpenGL. I've used

`std::vector`

`glBufferData()`

`std::vector`

`const GLvoid *`

`glBufferData()`

`typedef struct`

{

float x, y, z;

float nx, ny, nz;

float u, v;

}

Vertex;

vector<Vertex> vertices;

`glBufferData(GL_ARRAY_BUFFER, vertices.size() * 3 * sizeof(float), vertices, GL_STATIC_DRAW);`

I get the following (expected) error:

`error: cannot convert ‘std::vector<Vertex>’ to ‘const GLvoid*’ in argument passing`

How can I convert the vector to a type compatible with

`glBufferData()`

`vertices.size() * 3 * sizeof(float)`

Answer

If you have a `std::vector<T> v`

, you may obtain a `T*`

pointing to the start of the contiguous data (which is what OpenGL is after) with the expression `&v[0]`

.

In your case, this means passing a `Vertex*`

to `glBufferData`

:

```
glBufferData(
GL_ARRAY_BUFFER,
vertices.size() * sizeof(Vertex),
&vertices[0],
GL_STATIC_DRAW
);
```

Or like this, which is the same:

```
glBufferData(
GL_ARRAY_BUFFER,
vertices.size() * sizeof(Vertex),
&vertices.front(),
GL_STATIC_DRAW
);
```

You can rely on implicit conversion from `Vertex*`

to `void const*`

here; that should not pose a problem.