[英]C++ Pointer as DWORD
In C++, can I simply cast a pointer to a DWORD? 在C ++中,我可以简单地将指针转换为DWORD吗?
MyClass * thing;
DWORD myPtr = (DWORD)thing;
Would that work? 那行得通吗?
In windows its quite common to pass pointers in such way, for example in windows messages. 在Windows中,以这种方式传递指针是很常见的,例如在Windows消息中。 LPARAM is a typedef for LONG_PTR and quite often is used to pass pointers to some structures.
LPARAM是LONG_PTR的typedef,经常用于将指针传递给某些结构。 You should use
reinterpret_cast<DWORD_PTR>(thing)
for casting. 您应该使用
reinterpret_cast<DWORD_PTR>(thing)
进行投射。
You undoubtedly can do it. 您无疑可以做到。
Whether it would work will depend on the environment and what you want it to do. 它是否有效取决于环境和您想要做什么。
On 32-bit Windows 1 (the most common place to see DWORD
) it'll normally be fine. 在32位Windows 1 (最常见的
DWORD
)上,通常会没问题。 On a 64-bit Windows (where you also see DWORD
, but not nearly as much) it generally won't. 在64位Windows(您还会在其中看到
DWORD
,但DWORD
)上,通常不会。
No, in a 64 bit process, a pointer is 64 bits but a DWORD is only 32 bits. 不,在64位处理中,指针是64位,而DWORD只有32位。 Use a DWORD_PTR.
使用DWORD_PTR。
http://en.cppreference.com/w/cpp/language/explicit_cast http://en.cppreference.com/w/cpp/language/explicit_cast
Read that, understand that, avoid C-style casts because they hide a lot. 读那本书,了解那一点,避免使用C样式转换,因为它们隐藏很多。
Doing so may be able to be done, but would make no sense, for example DWORD is 4 bytes and a pointer (these days) is 8. 这样做也许可以完成,但毫无意义,例如DWORD为4个字节,而指针(这些天)为8。
reinterpret_cast<DWORD&>(myPtr);
Should work, but it may be undefined or truncate, if anything will work that will! 应该可以,但是如果有任何可行的方法,它可能是未定义或截断的!
BTW, reinterpret_cast
is the C++ way of saying "Trust me my dear compiler, I know what I'm doing" - it attempts to interpret the bits (0s and 1s) of one thing as another, regardless of how much sense that makes. 顺便说一句,
reinterpret_cast
是C ++的一种说法,“相信我亲爱的编译器,我知道我在做什么”-它试图将一件事的位(0和1)解释为另一件事,而不管其含义如何。
A legitimate use though is the famous 1/sqrt hack ;) 虽然合法使用是著名的1 / sqrt hack;)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.