简体   繁体   中英

Is cast to void* in a glVertexAttribPointer call a legal C++?

This is really a question about C++, not OpenGL. I'm following this tutorial on OpenGL (I've just started), and the author uses C++ (not C). My problem is that glVertexAttribPointer takes an offset parameter as const void* . Since this parameter simply tells OpenGL where a given vertex attribute appears for the first time in the array of vertices that was copied with glBufferData() , I would expect that it should be of std::ptrdiff_t type. This post on SO explains the reason why void* is used as an argument type, but I wonder why such a usage is legal in C++. For instance, the mentioned tutorial simply casts to void* the value of the offset in bytes, like in the call below:

glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 6 * sizeof(float), (void*)(3* sizeof(float)));

It seems to me that this approach cannot be legal because the cpprefence documentation of reinterpret_cast says

A value of any integral or enumeration type can be converted to a pointer type. A pointer converted to an integer of sufficient size and back to the same pointer type is guaranteed to have its original value, otherwise the resulting pointer cannot be dereferenced safely (the round-trip conversion in the opposite direction is not guaranteed the same pointer may have multiple integer representations)

So, if I understand this correctly, the std::ptrdiff_t value of the offset (which seems to be the one that is needed here) can be lost after the cast to void* . What do I miss?

"Not guaranteed " does not mean "guaranteed to fail"; it means "not guaranteed". Which means the implementation may or may not preserve the conversion.

The glVertexAttribPointer API requires an implementation of C or C++ that preserves integer->pointer->integer conversions. Much like it requires a C or C++ implementation that offers IEEE-754 floating-point types, as well as 8/16/32-bit integers.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM