如何检查一个void *指针是否可以安全地转换成别的东西? [英] How to check if a void* pointer can be safely cast to something else?
问题描述
假设我有这个函数,它是一些gui工具包的一部分:
Let's say I have this function, which is part of some gui toolkit:
typedef struct _My_Struct My_Struct;
/* struct ... */
void paint_handler( void* data )
{
if ( IS_MY_STRUCT(data) ) /* <-- can I do something like this? */
{
My_Struct* str = (My_Struct*) data;
}
}
/* in main() */
My_Struct s;
signal_connect( SIGNAL_PAINT, &paint_handler, (void*) &s ); /* sent s as a void* */
由于paint_handler也会被GUI工具包主循环与其他参数,我不能总是确保我接收的参数将永远是一个指针 s
。
Since the paint_handler will also be called by the GUI toolkit's main loop with other arguments, I cannot always be sure that the parameter I am receiving will always be a pointer to s
.
我可以在 paint_handler
函数中执行 IS_MY_STRUCT
,以检查我接收的参数是否可以安全回到 My_Struct *
?
Can I do something like IS_MY_STRUCT
in the paint_handler
function to check that the parameter I am receiving can be safely cast back to My_Struct*
?
推荐答案
> void 指针会丢失其所有类型信息,因此,单独,您不能检查是否可以安全地转换。由程序员知道是否可以将 void *
安全地转换为类型。
Your void
pointer looses all its type information, so by that alone, you cannot check if it can be cast safely. It's up to the programmer to know if a void*
can be cast safely to a type.
这篇关于如何检查一个void *指针是否可以安全地转换成别的东西?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!