Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

int to void* - avoiding c-style cast?

I need to cast an int (which specifies a byte offset) to a const void*. The only solution that really works for me are c-style casts:

int offset = 6*sizeof(GLfloat);
glVertexAttribPointer(1,3,GL_FLOAT,GL_FALSE,0,(void*)offset);

I want to get rid of the c-style cast, but I dont't find a working solution. I tried

static_cast<void*>(&offset)

and it compiles, but that cannot be the right solution (whole output is different with this approach). What is here the right solution?

Link to documentation of glVertexAttribPointer: Link

like image 927
Matthias Preu Avatar asked Oct 05 '14 10:10

Matthias Preu


2 Answers

Considering that it's a hopeless case (See the link provided by derhass), the probably best approach is to concentrate the questionable code in one place, tack an appropriately snide remark onto it and at least keep the remaining code clean:

/**
 * Overload/wrapper around OpenGL's glVertexAttribIPointer, which avoids
 * code smell due to shady pointer arithmetic at the place of call.
 *
 * See also:
 * https://www.opengl.org/registry/specs/ARB/vertex_buffer_object.txt
 * https://www.opengl.org/sdk/docs/man/html/glVertexAttribPointer.xhtml
 */
void glVertexAttribPointer(GLuint index, GLint size, GLenum type, GLsizei stride, size_t offset)
{
    GLvoid const* pointer = static_cast<char const*>(0) + offset;
    return glVertexAttribPointer(index, size, type, stride, offset);
}
like image 91
Ulrich Eckhardt Avatar answered Oct 24 '22 11:10

Ulrich Eckhardt


Use this instead of void pointer:

intptr_t

which is declared in header file file cstdint

and inter-convert from pointer by using

reinterpret_cast

Read this in case of any problem: http://msdn.microsoft.com/en-us/library/e0w9f63b.aspx

like image 41
Anant Simran Singh Avatar answered Oct 24 '22 10:10

Anant Simran Singh