我尝试使用Visual Studio 2013为x64构建我的Win32 API项目。但路由的WindowProc回调无法正常工作。我正在使用SetWindowLongPtr / GetWindowLongPtr和GWLP_USERDATA来存储我的窗口的this指针。在过去,我使用SetWindowLong / GetWindowLong和GWL_USERDATA用于此目的 - 但这些在x64上消失了。但是在x86上一切仍然正常(即使使用SetWindowLongPtr / GetWindowLongPtr和GWLP_USERDATA),但在x64上,一旦我尝试访问我的成员函数WindowProc中的任何方法/成员,就会出现访问冲突。
#include <windows.h>
#include <stdio.h>
#include "main.h"
class Window{
public:
Window(const char* title, const float width, const float height){
char windowClass[255];
sprintf_s(windowClass, "WindowClass%s", title);
WNDCLASSEX wc;
ZeroMemory(&wc, sizeof(WNDCLASSEX));
wc.cbSize = sizeof(WNDCLASSEX);
wc.style = CS_HREDRAW | CS_VREDRAW | CS_OWNDC;
wc.lpfnWndProc = WindowProcRouter;
wc.hInstance = nullptr;
wc.hCursor = LoadCursor(nullptr, IDC_ARROW);
wc.hbrBackground = (HBRUSH)COLOR_WINDOW;
wc.lpszClassName = windowClass;
RegisterClassEx(&wc);
DWORD dwStyle = WS_CAPTION | WS_MINIMIZEBOX | WS_SYSMENU;
RECT WindowRect;
WindowRect.left = (long)0;
WindowRect.right = (long)width;
WindowRect.top = (long)0;
WindowRect.bottom = (long)height;
AdjustWindowRect(&WindowRect, dwStyle, FALSE);
hWnd = CreateWindowEx(0,
windowClass,
title,
dwStyle,
0, 0,
WindowRect.right - WindowRect.left,
WindowRect.bottom - WindowRect.top,
nullptr,
nullptr,
wc.hInstance,
(LPVOID) this);
wc.hbrBackground = (HBRUSH)COLOR_WINDOW;
ShowWindow(hWnd, SW_SHOW);
SetFocus(hWnd);
closed = false;
}
static LRESULT CALLBACK Window::WindowProcRouter(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam){
LRESULT returnValue = 0;
Window* pWnd = nullptr;
if (uMsg == WM_NCCREATE){
SetWindowLongPtr(hWnd, GWLP_USERDATA,
(long)((LPCREATESTRUCT(lParam))->lpCreateParams));
}
pWnd = (Window*)GetWindowLongPtr(hWnd, GWLP_USERDATA);
if (pWnd){
returnValue = pWnd->WindowProc(hWnd, uMsg, wParam, lParam);
}
else{
returnValue = DefWindowProc(hWnd, uMsg, wParam, lParam);
}
return returnValue;
}
LRESULT CALLBACK Window::WindowProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam){
switch (uMsg){
case WM_DESTROY:
closed = true;
PostQuitMessage(0);
break;
default:
break;
}
return DefWindowProc(hWnd, uMsg, wParam, lParam);
}
bool Window::isClosed(){
return closed;
}
Window::~Window(){
if (hWnd && !DestroyWindow(hWnd)){
hWnd = nullptr;
}
}
private:
HWND hWnd;
bool closed;
};
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow){
Window win("Title", 640, 480);
MSG msg;
while(!win.isClosed()){
while (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)){
TranslateMessage(&msg);
DispatchMessage(&msg);
}
}
}
在closed = true;
的{{1}}行发生了违规行为。
有什么想法吗?
答案 0 :(得分:7)
您将lpCreateParams
强制转换为long
,它会丢弃指针的前32位。这是您将GWL_USERDATA
更改为GWLP_USERDATA
时应该考虑的内容。这就是我们改名的原因。强制您查看所有受影响的代码并进行相应的更改以支持64位操作。 (这也是你在调试过程中应该注意到的。“嗯,this
的值是正确的,除了前32位设置为零。我不知道......”)
答案 1 :(得分:4)
当您致电SetWindowLongPtr()
时,您将值转换为long
,这意味着在x64版本中您将丢失前32位。
你应该转为DWORD_PTR
。