windows 64 位机器上的 DWORD 和 DWORD_PTR
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5867904/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
DWORD and DWORD_PTR on 64 bit machine
提问by Nikhil
There are few *_PTR
types added to the Windows API in order to support Win64's 64bit addressing.
*_PTR
为支持 Win64 的 64 位寻址,向 Windows API 添加的类型很少。
SetItemData(int nIndex,DWORD_PTR dwItemData)
This API works for both 64 and 32 bit machines when I pass second parameter as DWORD
.
当我将第二个参数作为DWORD
.
I want to know, if this particular API will fail on 64 bit machine, if I pass the second parameter as DWORD
. How can I test the fail scenario?
我想知道,如果这个特定的 API 会在 64 位机器上失败,如果我将第二个参数作为DWORD
. 如何测试失败场景?
Thanks, Nikhil
谢谢,尼基尔
采纳答案by Frédéric Hamidi
The function will not fail if you pass a DWORD
, because it fits into a DWORD_PTR
. A pointer, however, is guaranteed to fit into a DWORD_PTR
but notinto a DWORD
on 64-bit platforms.
如果您传递 a DWORD
,该函数不会失败,因为它适合 a DWORD_PTR
。一个指针,然而,是保证装配到DWORD_PTR
但不为DWORD
在64位平台。
Thus, this code is correct:
因此,这段代码是正确的:
int *before_ptr = new int;
yourListBox.SetItemData(index, (DWORD_PTR) before_ptr);
int *after_ptr = (int *) yourListBox.GetItemData(index);
ASSERT(before_ptr == after_ptr); // Succeeds.
delete after_ptr; // Works.
But this code is wrong and will silently truncate the pointer to its lower 32 bits:
但是这段代码是错误的,它会默默地将指针截断到它的低 32 位:
int *before_ptr = new int;
yourListBox.SetItemData(index, (DWORD) before_ptr);
int *after_ptr = (int *) yourListBox.GetItemData(index);
ASSERT(before_ptr == after_ptr); // Fails.
delete after_ptr; // Undefined behavior, might corrupt the heap.