64 位机器上的 DWORD 和 DWORD_PTR
为了支持 Win64 的 64 位寻址,向 Windows API 添加了一些 *_PTR
类型.
There are few *_PTR
types added to the Windows API in order to support Win64's 64bit addressing.
SetItemData(int nIndex,DWORD_PTR dwItemData)
当我将第二个参数作为 DWORD
传递时,此 API 适用于 64 位和 32 位机器.
This API works for both 64 and 32 bit machines when I pass second parameter as DWORD
.
我想知道,如果我将第二个参数作为 DWORD
传递,这个特定的 API 在 64 位机器上是否会失败.如何测试失败场景?
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?
谢谢,尼基尔
推荐答案
如果你传递一个 DWORD
,函数不会失败,因为它适合 DWORD_PTR
.但是,在 64 位平台上,可以保证指针适合 DWORD_PTR
,但 不 适合 DWORD
.
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 not into a DWORD
on 64-bit platforms.
因此,这段代码是正确的:
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.
但是这段代码是错误的,它会默默地将指针截断到它的低 32 位:
But this code is wrong and will silently truncate the pointer to its lower 32 bits:
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.
相关文章