Search code examples
openglc++11vertex-buffer

How to cast int to const GLvoid*?


In my cross platform OpenGL application I want to draw using vertex buffer objects. However I run into problems invoking glDrawRangeElements.

glDrawRangeElements(GL_TRIANGLES, start, start + count, count, 
            GL_UNSIGNED_INT,  static_cast<GLvoid *>  (start * sizeof(unsigned int)));

The compiler (CLang on Mac OS X) does not like the last argument "error: cannot cast from type 'unsigned long' to pointer type 'GLvoid *' (aka 'void *')". OpenGL API defines the type of last arguments as const GLvoid * and expects a pointer when this api is used with vertex arrays. However I understand that when vertex buffer objects are employed instead of pointer, one is expected to pass an integer value representing offset into buffer data. This is what I am trying to do and thus I have to cast. How do I reconcile api requirements with compiler imposing rigorous checks?


Solution

  • I got it to compile using CLang and c++11 when I used ancient c style casting.

    glDrawRangeElements(GL_TRIANGLES, start, start + count, count, GL_UNSIGNED_INT,
            (GLvoid *)  (start * sizeof(unsigned int)));
    

    Alternatives that I liked less but were also accepted by compiler were

    glDrawRangeElements(GL_TRIANGLES, start, start + count, count, GL_UNSIGNED_INT,
      reinterpret_cast<GLvoid *>(static_cast<uintptr_t>(start * sizeof(unsigned int))));
    
    
    glDrawRangeElements(GL_TRIANGLES, start, start + count, count, GL_UNSIGNED_INT,
        (char *)(0) +  start * sizeof(unsigned int));