Game Development Reference
In-Depth Information
Listing 26-2. An Example Bad Pointer Cast
bool CompareAddresses(void* pAddress1, void* pAddress2)
{
uint32_t address1 = reinterpret_cast<uint32_t>(pAddress1);
uint32_t address2 = reinterpret_cast<uint32_t>(pAddress2);
return address1 == address2;
}
There are a handful of cases where you might be required to compare the values of two addresses
and you could case the pointers to 32-bit unsigned ints to achieve this comparison. This code,
however, is not portable. The following two hexadecimal values represent different memory locations
on 64-bit computers:
0xFFFFFFFF00000000
0x0000000000000000
If you cast these two values to uint32_t the two hex values stored in the unsigned integers will be:
0x00000000
0x00000000
The CompareAddresses function would return true for two different addresses because the upper 32
bits of the 64-bit addresses have been narrowed without warning by reinterpret_cast . This function
would always work on systems with 32-bit pointers or less and only break on 64-bit systems.
Listing 26-3 contains the solution to this problem.
Listing 26-3. An Example of a Good Pointer Comparison
bool CompareAddresses(void* pAddress1, void* pAddress2)
{
uintptr_t address1 = reinterpret_cast<uintptr_t>(pAddress1);
uintptr_t address2 = reinterpret_cast<uintptr_t>(pAddress2);
return address1 == address2;
}
The cstdint header provides intptr_t and uintptr_t , which are signed and unsigned integers with
enough bytes to completely store an address on your target platform. You should always use these
types when casting pointers into integer values if you would like to write portable code!
Now that we've covered the different issues we can encounter with different-sized integers and
pointers on different platforms, we'll look at how we can provide different implementations of classes
on different platforms.
Using the Preprocessor to Determine Target Platform
Straight off the bat in this section, I'll show you a header file that defines preprocessor macros
to determine which platform you are currently targeting. Listing 26-4 contains the code for the
Platforms.h header file.
 
Search WWH ::




Custom Search