void* is literally float, how to cast?

不想你离开。 提交于 2019-12-05 04:44:13

Try using pointers:

void *theValueAsVoidPtr = // whatever

float flt = *(float *)&theValueAsVoidPtr;

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!