void* is literally float, how to cast?

て烟熏妆下的殇ゞ 提交于 2019-12-07 01:49:02

问题


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 pretty much any other *-type. I also know that I expect a float at the end somewhere from this function.

So I cast the void* to a float* and dereference the float*, crash. darn!. I debug the code and in gdb let it evaluate (float)voidPtr and low and behold the value is what I expect and need!

But wait, it's impossible to the same during compile time. If I write float number = (float)voidPtr; it doesn't compile, which is understandable.

So now the question, how do I get my float out of this fricking void*?

EDIT: Thanks to H2CO3 this was solved, but I see lots of answers and comments appearing and dissappering not believing that I could do (float)voidPtr in gdb. here is the screenshot.


回答1:


Try using pointers:

void *theValueAsVoidPtr = // whatever

float flt = *(float *)&theValueAsVoidPtr;



回答2:


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.



来源:https://stackoverflow.com/questions/15313658/void-is-literally-float-how-to-cast

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