[英]void* is literally float, how to cast?
So I'm using this C library in my C++ app, and one of the functions returns a void*. 因此,我在C ++应用程序中使用了这个C库,其中一个函数返回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.
现在我对纯C并不是最精明的,但是听说可以将void *转换为几乎所有其他*类型。 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. 因此,我将void *强制转换为float *,然后取消引用float *,导致崩溃。 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! 我调试了代码,并在gdb中让它评估
(float)voidPtr
和low,并认为该值是我期望和需要的!
But wait, it's impossible to the same during compile time. 但是,等等,在编译期间不可能做到相同。 If I write
float number = (float)voidPtr;
如果我写
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. 编辑:由于使用了H2CO3,因此得以解决,但是我看到很多答案和评论出现,并且在不相信我可以在gdb中做到(float)voidPtr的情况下消失。 here is the screenshot.
这是屏幕截图。
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 *
. 如果我理解正确,则您的库将在声明的类型为
void *
的变量中返回浮点值 。 The safest way to get it back out again is with a union
: 再次收回它的最安全方法是使用
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. 与接受的答案中的方法不同,这不会触发未定义的行为。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.