In cases where you really have a good reason to truncate pointers, you can make /Wp64
accept your code by stacking multiple casts. These cases are rare. One example: device drivers for legacy PCI devices, doing DMA, with memory allocated below the 4GB limit. (Note: there is also the PtrToUlong()
macro, which will make your intentions clearer.)
This single cast will produce a warning:
const char* p = "abc";
unsigned int u = reinterpret_cast<unsigned int>(p);
wp64.cpp(10) : warning C4311: 'reinterpret_cast' : pointer truncation from 'const char *' to 'unsigned int'
But these stacked casts will not:
const char* p = "abc";
unsigned int u = static_cast<unsigned int>(reinterpret_cast<uintptr_t>(p));
I'm not able to reproduce your warning with the version of the compiler that I have installed, but I suspect that your problem is related to the fact that you're casting a 64-bit unsigned size_t
into a 32-bit signed int
.
You might have better luck if you stack multiple casts to do the 64-bit to 32-bit conversion and the unsigned-to-signed conversion:
const char* s = "abcdef";
int l = static_cast<int>(static_cast<intptr_t>(strlen(s)));
Also, if you build both x86 and x64 binaries, you can disable /Wp64
for your 32-bit builds so that you don't have to annotate any types with __w64
. Using /Wp64
for your 64-bit builds will catch a lot of bugs.