通过 void * 投射枚举
我正在尝试将一些旧的 32 位代码转换为 64 位。我收到的最常见的警告之一是:
warning:cast ofpointer to integer of different size
当函数调用 pthread_create 接受 void * 用于将数据传递给新线程。调用线程在 void * 中放入一个枚举(因此 64 位中的大小不匹配)。这是代码:
typedef enum {
zero,
one,
two
}numbers_e;
some_function(...)
{
numbers_e mydata=zero;
...
pthread_create(..., (void *)mydata);
...
}
我设法克服了这个警告:
pthread_create(..., (void *)0 + my_data);
这个解决方案非常丑陋(我正在考虑是否最好将警告保留在使用它的代码附近的大注释中)。还有其他解决方案吗?
I'm trying to convert some old 32 bit code to 64 bit. One of the more frequent warnings I get is:
warning: cast of pointer to integer of different size
this happens when a function calls pthread_create which accepts a void * for passing data to the new thread. The calling thread puts in that void * an enum (hence the size mismatch in 64bit). Here's the code:
typedef enum {
zero,
one,
two
}numbers_e;
some_function(...)
{
numbers_e mydata=zero;
...
pthread_create(..., (void *)mydata);
...
}
I managed to overcome the warning with this:
pthread_create(..., (void *)0 + my_data);
this solution is very ugly (and I'm pondering if it's better to leave the warning as is with a big remark near the code using it). Is there another solution ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
你的解决方案不仅丑陋,而且是未定义的行为(UB),可能会在将来给你带来问题:
void*
指针上的算术是非标准的,必须是一个编译器
要避免第一个,您可以使用
(char*)0 + my_data
,但这仍然会留下第二个。您可以做什么
uintptr_t
。这是一种保证的类型与
void*
兼容(如果存在)。它存在于大多数现代平台。优点是你的代码无法编译
它不存在的平台,明确表明您已经拥有
那么,改变一些东西。
pthreads 是
为两者设计的,但是,您必须修改被调用函数的源代码,因此您最好将其更改为第二个,这应该是这样的。
your solution is not only ugly, it is undefined behaviour (UB) that could cause you problems in the future:
void*
pointers is non standard and must be anextension of your compiler
To avoid the first you could use
(char*)0 + my_data
, but this would still leave you with the second.What you could do
uintptr_t
. this is a type that is guaranteed tobe compatible with
void*
, if it exists. It exists on most modernplatforms. The advatage would be that your code wouldn't compile on
platforms where it doesn't exist, a clear indication that you'd have
to change something, then.
pthreads are designed
For both you'd have to modify the source of the called function, though, so you'd well change it to the second, the way how this should be.
是的,传递对象的地址。
只要
mydata
在某处仍然可用,编辑就应该是安全的。Yeah, pass the address of the object.
That should be safe edit as long as
mydata
remains available somewhere.将数据作为指针传递几乎不是一个好主意,但如果有很多代码执行此操作,请保持原样。
否则,我会按照 cnicutar 的建议传递地址。
请记住,如果 mydata 范围在线程开始之前结束,则可能会出现损坏问题。
passing a data as a pointer is hardly a good idea, but if there is a lot of code that does it - just leave it as is.
otherwise, I would pass the address as cnicutar suggested.
keep in mind that if mydata scope ends before the thread begins you may have a corruption problem.