Search code examples
c++castingglm-math

C++ Cast float* to glm::vec3


How can I cast an array of floats int the form float* to glm::vec3? I thought I had done it before but I lost my hdd. I tried a few C-style and static_casts but I can't seem to get it working.


Solution

  • The glm documentation tells you how to cast from vec3 to a float*.

    #include <glm/glm.hpp>
    #include <glm/gtc/type_ptr.hpp>
    glm::vec3 aVector(3);
    glm::mat4 someMatrix(1.0);
    glUniform3fv(uniformLoc, 1, glm::value_ptr(aVector));
    glUniformMatrix4fv(uniformMatrixLoc,
           1, GL_FALSE, glm::value_ptr(someMatrix));
    

    You use glm::value_ptr.

    The documentation doesn't say this explicitly, however it seems clear that glm intends these types to be 'layout compatible' with arrays, so that they can be used directly with OpenGL functions. If so then you can cast from an array to vec3 using the following cast:

    float arr[] = { 1.f, 0.f, 0.f };
    vec3<float> *v = reinterpret_cast<vec3<float>*>(arr);
    

    You should probably wrap this up in your own utility function because you don't want to be scattering this sort of cast all over your codebase.