windows 用于存储对象指针的 GWL_USERDATA 的替代方法是什么?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23083/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 11:06:54  来源:igfitidea点击:

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

windowswinapiwin64

提问by Benjamin Pollack

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 thisin 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?

在我处理的 Windows 应用程序中,我们有一个直接位于 Win32 之上的自定义框架(不要问)。当我们创建一个窗口时,我们通常的做法是通过 放入this窗口的用户数据区SetWindowLong(hwnd, GWL_USERDATA, this),这样我们就可以有一个类似 MFC 的回调或一个紧密集成的WndProc,依赖。问题是这在 Win64 上不起作用,因为 LONG 只有 32 位宽。这个问题的更好解决方案是在 32 位和 64 位系统上都有效吗?

回答by Chris

SetWindowLongPtrwas created to replace SetWindowLongin these instances. It's LONG_PTR parameter allows you to store a pointer for 32-bit or 64-bit compilations.

创建SetWindowLongPtr是为了在这些实例中替换SetWindowLong。它的 LONG_PTR 参数允许您存储 32 位或 64 位编译的指针。

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:

另外不要忘记现在要检索指针,您必须使用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;

回答by Anders

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

另一种选择是 SetProp/RemoveProp(当您对已经使用 GWLP_USERDATA 的窗口进行子类化时)

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

另一个不错的选择是 WNDPROC 的 ATL 样式 thunking,有关更多信息,请参阅