2

Both are used for storing addresses and doing pointer arithmetic, both are defined in WinAPI, when should I use a uintptr_t (cstdint) vs a DWORD_PTR (Windows.h)? Both are 32bits and 64bits in x86 and x86_64 respectively

A DWORD_PTR is an unsigned long type used for pointer precision. It is used when casting a pointer to an unsigned long type to perform pointer arithmetic. DWORD_PTR is also commonly used for general 32-bit parameters that have been extended to 64 bits in 64-bit Windows.

I do not intend for my code to be portable, I'm stuck with WinAPI. What type is the best use case?

Thomas Dickey
  • 51,086
  • 7
  • 70
  • 105
otc
  • 431
  • 4
  • 15
  • 2
    I never use Windows typedefs unless directly working against Windows API functions. And even then, I end up using `reinterpret_cast`. – Class Skeleton Aug 19 '15 at 15:46
  • I'd pick `uintptr_t`, if only because it doesn't SCREAM AT YOU. And for the fact that the "DWORD" is a lie in 64 bits, and code that lies to you is horrible. ("sizeof(DWORD) bytes should be enough for anyone"...) – molbdnilo Aug 19 '15 at 15:46

2 Answers2

8

Prefer uintptr_t it is part of the C++ standard as of C++11 and later. DWORD_PTR is specific to Visual C++ and is therefore not portable.

While Visual C++ may choose to implement uintptr_t as a DWORD_PTR or unsigned long under the hood, that is up to them to do, you are safer sticking to the standard library.

Cory Kramer
  • 114,268
  • 16
  • 167
  • 218
2

uintptr_t (actually std::uintptr_t in C++) is not defined in WinAPI, it's defined in the standard C++ header <cstdint>. The standard C++ library is defined by the C++ language and has nothing to do with WinAPI.

If you want to use the type for interaction with WinAPI, use DWORD_PTR as that's what the WinAPI functions expect.

For other uses, it's really up to you. I prefer standard types over platform-specific ones, so I'd use std::uintptr_t, but either is possible.

Angew is no longer proud of SO
  • 167,307
  • 17
  • 350
  • 455