Void * literally swims, how to throw?

So, I use this C library in my C ++ application, and one of the functions returns void *. Now I'm not the sharpest with pure C, but I heard that void * can be applied to any other * type. I also know that I expect the float to be somewhere close to this function.

So, I passed void * to float * and dereferenced float *, crash. darn!. I am debugging the code and in gdb I let it evaluate (float)voidPtr and low, and here it is what I expect and need!

But wait, this is not possible during compilation. If I write float number = (float)voidPtr; , it does not compile, which is understandable.

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

EDIT: Thanks to H2CO3 this was resolved, but I see a lot of answers and comments appearing and disappearing, not believing that I could (float) voidPtr in gdb. here is a screenshot.

enter image description here

+6
source share
2 answers

Try using pointers:

 void *theValueAsVoidPtr = // whatever float flt = *(float *)&theValueAsVoidPtr; 
+12
source

If I understand correctly, your library returns a float value in a variable whose declared type is void * . The safest way to get it back is with 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 cause undefined behavior.

+8
source

All Articles