DWORD and DWORD_PTR on 64 bit machine

后端 未结 1 1939
走了就别回头了
走了就别回头了 2021-01-06 10:35

There are few *_PTR types added to the Windows API in order to support Win64\'s 64bit addressing.

SetItemData(int nIndex,DWORD_PTR dwItemData)
<         


        
相关标签:
1条回答
  • 2021-01-06 11:13

    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.
    

    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.
    
    0 讨论(0)
提交回复
热议问题