问题
Quoting from http://msdn.microsoft.com/en-us/library/windows/desktop/aa384242%28v=vs.85%29.aspx
Use UINT_PTR and INT_PTR where appropriate (and if you are uncertain whether they are required, there is no harm in using them just in case). Do not cast your pointers to the types ULONG, LONG, INT, UINT, or DWORD.
Can I safely assume that converting all referenced of DWORD to UNIT_PTR in an existing 32 bit Codeline is safe without any side effects?
Is there are other recommended guidelines to port a 32 bit code which has referenced to DWORD through out the codeline?
回答1:
This is too crude. Just let the compiler do the work for you, enable warning 4302 so it will tell you when a pointer value gets truncated. Put the #pragma in a good place, the pre-compiled header file would be ideal. Or specify the /we4302
compiler option.
#pragma warning(default:4302)
int main()
{
int* p = 0;
long bad = (long)p; // C4302: 'type cast' : truncation from int* to long
return 0;
}
The /Wp64 compile option can be useful as well, for a sniff anyway, but it has problems.
回答2:
You only need to use INT_PTR
or UINT_PTR
if you are planning to store a pointer in the variable (including various forms of HANDLE
). If it's just a regular integral value, then it won't matter.
I expect that you'll get at least some warnings for "trying to store a larger type in a smaller type" if you blindly translated all DWORD
to UINT_PTR
. [That is, when you compile the code for 64-bit, as in 32-bit code, the type UINT_PTR
is the same as DWORD
so you may not get any warnings in that case].
回答3:
To add on @MatsPetersson answer -
The reason DWORD
is widely used to hold addresses is that it matches the pointer size on 32-bit architecture.
Best practice is to use dedicated types for variables holding addresses. That's what UINT_PTR
& INT_PTR
are for - they are correct for both 32 and 64-bit targets since their definition is set correctly according to compilation target. Actually, you can browse the MS headers and see for yourself the actual primitive types that these types correspond to.
Whenever the variable is used for data other than address, actual type should be defined according to the stored data and normally won't depend on underlying computer architecture - DWORD
will remain DWORD
, WORD
will remain WORD
etc.
来源:https://stackoverflow.com/questions/15096939/clarification-porting-32-to-64-bit