void* is literally float, how to cast?

前端 未结 2 1431
天涯浪人
天涯浪人 2021-01-05 03:18

So I\'m using this C library in my C++ app, and one of the functions returns a void*. Now I\'m not the sharpest with pure C, but have heard that a void* can be cast to prett

2条回答
  •  难免孤独
    2021-01-05 04:07

    If I understand correctly, your library is returning a float value in a variable whose declared type is void *. The safest way to get it back out again is with a union:

    #include 
    static_assert(sizeof(float) == sizeof(void *));
    
    union extract_float {
        float vf;
        void * vp;
    };
    
    float foo(...)
    {
        union extract_float ef;
        ef.vp = problematic_library_call(...);
        return ef.vf;
    }
    

    Unlike the approach in the accepted answer, this does not trigger undefined behavior.

提交回复
热议问题