Quote:Original post by pDK
Wonderful! I actualy just found another method just as you posted:
inline DWORD PtoDW(WPOINT p){ return *((DWORD*)&p);}
What are the advantages between the two? Does this run into the padding issue? (Also, what can I search to find more information about this padding issue; I am unfimilar with it).
For correctness, Conner Mc Cloud's recommendation is best.
With your solution there are two issues:
1) Padding because of alignment: Some machines (for instance Itanium 64 bit) require all data accesses to by aligned to their type boundary. For instance, if you have the following struct
struct X{ char A; char B; int32 C;};
The size of this struct might be two bytes more than what you expect. This is because all accesses to 32 bit integer C must be aligned to the 4 byte boundary. So the compiler usually ends up padding the space between B and C.
Notice that if the struct was
struct X{ int32 C; char A; char B;};
the size would be 6 bytes, as you expect.
The way to get around padding by the compiler is to tell the compiler to not pack is to use the pragma pack. For instance by using #pragma pack(1)
MSDN link on
Data Alignment2) Byte Order or Endianness: Some machines store lower order bits of types at lower memory locations. In your case if WORD is 16 bit, you might have a problem.. For instance if you store 0xDEAD in the WORD x and 0xCAFE in the word y and read back using the memory location of the struct into a DWORD you might end up with 0xCAFEDEAD instead of the 0xDEADCAFE which you expect.
Wikipedia link on
Endiannessin C++,a struct is just another class, so you have to provide a conversion operator to do type conversions like (DWORD)WPOINT. That is the reason your compile failed initially.
[EDIT] beaten by 2 posts!