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

馋奶兔 提交于 2019-12-03 23:15:43

问题


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 this in the window's user data area via SetWindowLong(hwnd, GWL_USERDATA, this), which allows us to have an MFC-like callback or a tightly integrated WndProc, depending. The problem is that this will not work on Win64, since LONG is only 32-bits wide. What's a better solution to this problem that works on both 32- and 64-bit systems?


回答1:


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;



回答2:


The other alternative is SetProp/RemoveProp (When you are subclassing a window that already uses GWLP_USERDATA)

Another good alternative is ATL style thunking of the WNDPROC, for more info on that, see

  • http://www.ragestorm.net/blogs/?cat=20
  • http://www.hackcraft.net/cpp/windowsThunk/


来源:https://stackoverflow.com/questions/23083/whats-an-alternative-to-gwl-userdata-for-storing-an-object-pointer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!