带指针的开关盒
可能的重复:
为什么不打开指针?
int main(int argc, char** argv)
{
void* not_a_pointer = 42;
switch(not_a_pointer)
{
case 42:
break;
}
return 0;
}
。
error: switch quantity not an integer
如何可移植地使用 switch-case 来获取指针类型变量的值?原因是我正在使用的 API 中的回调函数之一具有 void* 参数。
Possible Duplicate:
Why no switch on pointers?
int main(int argc, char** argv)
{
void* not_a_pointer = 42;
switch(not_a_pointer)
{
case 42:
break;
}
return 0;
}
.
error: switch quantity not an integer
How can I portably use a switch-case for the value of a variable with a pointer type? The reason for this is that one of the callback functions in an API I'm using has a void* argument.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
尝试转换为
intptr_t
,这是一个整数类型:等等...
try casting to
intptr_t
, which is an integer type:etc...
如果您知道
void*
并不是真正的指针,请在尝试在 case 语句中使用它之前将其强制转换回int
。If you know that the
void*
isn't really a pointer, cast it back to anint
before trying to use it in the case statement.这应该有效:
This should work:
如果您想要将整数传递给传递
void *
的回调 API,目的是传递该整数的地址。请注意,这可能意味着您需要进行动态分配:然后在回调中:(
您可以将整数强制转换为
void *
并返回,但转换是实现-定义的void *
到intptr_t
/uintptr_t
到void *
往返需要保留值,但无论如何,反之则不然。)If you want to pass an integer to a callback API that passes a
void *
, the intention is that you pass the address of the integer. Note that this might mean you need to do dynamic allocation:Then in the callback:
(You can coerce an integer into a
void *
and back, but the conversions are implementation-defined. Thevoid *
tointptr_t
/uintptr_t
tovoid *
round-trip is required to be value preserving, but the inverse is not. It's ugly, anyway.).