简体   繁体   中英

C++ Pointer as DWORD

In C++, can I simply cast a pointer to a 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. LPARAM is a typedef for LONG_PTR and quite often is used to pass pointers to some structures. You should use reinterpret_cast<DWORD_PTR>(thing) for casting.

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. On a 64-bit Windows (where you also see DWORD , but not nearly as much) it generally won't.


  1. Or, more accurately, when compiled as a 32-bit executable that will run as a 32-bit process, regardless of the actual copy of Windows you happen to run that on.

No, in a 64 bit process, a pointer is 64 bits but a DWORD is only 32 bits. Use a DWORD_PTR.

http://en.cppreference.com/w/cpp/language/explicit_cast

Read that, understand that, avoid C-style casts because they hide a lot.

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.

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.

A legitimate use though is the famous 1/sqrt hack ;)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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