What's an alternative to GWL_USERDATA for storing an object pointer?

后端 未结 2 637
清酒与你
清酒与你 2021-01-01 10:25

In the Windows applications I work on, we have a custom framework that sits directly above Win32 (don\'t ask). When we create a window, our normal practice is to put

2条回答
  •  旧巷少年郎
    2021-01-01 10:43

    SetWindowLongPtr was created to replace SetWindowLong in these instances. It's LONG_PTR parameter allows you to store a pointer for 32-bit or 64-bit compilations.

    LONG_PTR SetWindowLongPtr(      
        HWND hWnd,
        int nIndex,
        LONG_PTR dwNewLong
    );
    

    Remember that the constants have changed too, so usage now looks like:

    SetWindowLongPtr(hWnd, GWLP_USERDATA, this);
    

    Also don't forget that now to retrieve the pointer, you must use GetWindowLongPtr:

    LONG_PTR GetWindowLongPtr(      
        HWND hWnd,
        int nIndex
    );
    

    And usage would look like (again, with changed constants):

    LONG_PTR lpUserData = GetWindowLongPtr(hWnd, GWLP_USERDATA);
    MyObject* pMyObject = (MyObject*)lpUserData;
    

提交回复
热议问题