Usage of uintptr_t vs DWORD_PTR

3.7k Views Asked by At

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?

2

There are 2 best solutions below

0
On BEST ANSWER

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.

0
On

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.