简体   繁体   English

转换指向uint64_t的指针

[英]Casting a pointer to uint64_t

对于const char *p (uint64_t)p ,假设两个选项都可以编译,是否可以保证(uint64_t)(uintptr_t)p(uint64_t)p具有相同的值?

It would be entirely legitimate (and even reasonable) for a compiler whose target used eg 48-bit pointers consisting of a 16-bit segment and 32-bit offset (segmented-model 80386 works that way) to handle conversions to uint64_t by storing the 16-bit segment and 32-bit offset to the destination object, leaving the remaining 16 bits holding whatever they happened to hold previously, provided that a conversion from uint64_t back to a pointer ignored the bits in question. 对于目标使用例如由16位段和32位偏移量组成的48位指针(分段模型80386以这种方式工作)以通过存储uint64_t转换的编译器,这是完全合法(甚至合理)的。 16位段和目标对象的32位偏移量,如果从uint64_t转换回指针的操作忽略了所讨论的位,则剩下的16位将保留之前发生的所有操作。 It would also be reasonable for such a platform to define uintptr_t as synonymous with uint64_t , and treat conversions to uint64_t the same way. 对于这样的平台,将uintptr_t定义为uint64_t同义词,并以相同的方式处理对uint64_t的转换也是合理的。

All that is guaranteed about conversions is that (void*)p==(void*)(uintptr_t)p . 关于转换的所有保证就是(void*)p==(void*)(uintptr_t)p There isn't guarantee that (uintptr_t)p == (uintptr_t)p , nor even that a pointer produced through a round-trip cast can be meaningfully dereferenced in any way whatsoever. 无法保证(uintptr_t)p == (uintptr_t)p ,甚至不能保证以任何方式有意义地取消对通过双向(uintptr_t)p == (uintptr_t)p产生的指针的引用。

That is only true if the range of numbers representable by uintptr_t are all representable by uint64_t . 仅当uintptr_t可表示的数字范围全部可由uint64_t表示时,这才是正确的。 As a practical matter, that will be true on 32-bit and 64-bit platforms, but not, for example, 128-bit platforms should they exist. 实际上,在32位和64位平台上确实如此,但是,例如,如果存在128位平台,则不是这样。

You really shouldn't rely on this, and just stick with uintptr_t where you need pointers as integers. 您真的不应该依赖于此,而只是在需要将指针作为整数的地方坚持使用uintptr_t

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM