void* is literally float, how to cast?

前端 未结 2 1420
天涯浪人
天涯浪人 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 03:48

    Try using pointers:

    void *theValueAsVoidPtr = // whatever
    
    float flt = *(float *)&theValueAsVoidPtr;
    
    0 讨论(0)
  • 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 <assert.h>
    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.

    0 讨论(0)
提交回复
热议问题