问题
I am following the Microsoft Docs for Windows api. I a currently on chapter 4 and trying to draw an ellipse. The m_pRenderTarget is declared in the class App.h. In the function OnRender(HWND hwnd) I am trying to use it to draw the geometry (ellipse). However, I am getting the following error:
Exception thrown: read access violation. this->m_pRenderTarget was 0x38.
After some debugging, I noticed the in the HRESULT App::CreateDeviceResources(HWND hwnd) function, m_pRenderTarget was for some reason not NULL, even though I initialized it as such and hadn't yet changed it (I don't think at least). My guess is that this is the problem. For reference, here is the relevant code:
#pragma once
#define MAX_LOADSTRING 100
#include "resource.h"
#include "pch.h"
class App
{
public:
App();
~App();
bool Init(HINSTANCE instance, int cmd);
int RunMessageLoop();
HINSTANCE getInstance() { return hInstance; }
private:
HINSTANCE hInstance;
TCHAR szTitle[MAX_LOADSTRING];
TCHAR szWindowClass[MAX_LOADSTRING];
ID2D1Factory* m_pD2DFactory;
ID2D1EllipseGeometry* m_pEllipseGeometry;
ID2D1HwndRenderTarget* m_pRenderTarget;
ID2D1SolidColorBrush* m_pBlackBrush;
ATOM RegisterClass();
BOOL InitInstance(int);
static LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam);
static INT_PTR CALLBACK About(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam);
HRESULT CreateDeviceIndependentResources();
HRESULT CreateDeviceResources(HWND hwnd);
HRESULT OnRender(HWND hwnd);
};
Here are the implementations:
#include "pch.h"
#include "App.h"
App::App()
: m_pRenderTarget(NULL)
{}
App::~App(){}
bool App::Init(HINSTANCE instance, int cmd)
{
hInstance = instance;
LoadString(hInstance, IDS_APP_TITLE, szTitle, MAX_LOADSTRING);
LoadString(hInstance, IDC_PRACTICE, szWindowClass, MAX_LOADSTRING);
RegisterClass();
if (!InitInstance(cmd))
return false;
return true;
}
int App::RunMessageLoop()
{
HACCEL hAccelTable;
hAccelTable = LoadAccelerators(hInstance, MAKEINTRESOURCE(IDC_PRACTICE));
MSG msg;
while (GetMessage(&msg, NULL, 0, 0))
{
if (!TranslateAccelerator(msg.hwnd, hAccelTable, &msg))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
}
return (int)msg.wParam;
}
//
// FUNCTION: MyRegisterClass()
//
// PURPOSE: Registers the window class.
//
ATOM App::RegisterClass()
{
WNDCLASSEXW wcex;
wcex.cbSize = sizeof(WNDCLASSEX);
wcex.style = CS_HREDRAW | CS_VREDRAW;
wcex.lpfnWndProc = WndProc;
wcex.cbClsExtra = 0;
wcex.cbWndExtra = 0;
wcex.hInstance = hInstance;
wcex.hIcon = LoadIcon(hInstance, MAKEINTRESOURCE(IDI_PRACTICE));
wcex.hCursor = LoadCursor(nullptr, IDC_ARROW);
wcex.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1);
wcex.lpszMenuName = MAKEINTRESOURCEW(IDC_PRACTICE);
wcex.lpszClassName = szWindowClass;
wcex.hIconSm = LoadIcon(wcex.hInstance, MAKEINTRESOURCE(IDI_SMALL));
return RegisterClassExW(&wcex);
}
BOOL App::InitInstance(int nCmdShow)
{
HRESULT hr = CreateDeviceIndependentResources();
if FAILED(hr)
{
return FALSE;
}
HWND hWnd;
hWnd = CreateWindow(szWindowClass, szTitle, WS_OVERLAPPEDWINDOW, CW_USEDEFAULT,
CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, 0, NULL, NULL, hInstance, this);
if (!hWnd)
{
return FALSE;
}
ShowWindow(hWnd, nCmdShow);
UpdateWindow(hWnd);
return TRUE;
}
//
// FUNCTION: WndProc(HWND, UINT, WPARAM, LPARAM)
//
// PURPOSE: Processes messages for the main window.
//
// WM_COMMAND - process the application menu
// WM_PAINT - Paint the main window
// WM_DESTROY - post a quit message and return
//
//
LRESULT CALLBACK App::WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
App* pApp;
if (message == WM_CREATE)
{
LPCREATESTRUCT pcs = (LPCREATESTRUCT)lParam;
pApp = (App*)pcs->lpCreateParams;
::SetWindowLongPtrW(hWnd, GWLP_USERDATA, PtrToUlong(pApp));
return TRUE;
}
else
{
pApp = reinterpret_cast<App*>(static_cast<LONG_PTR>(::GetWindowLongPtrW(hWnd, GWLP_USERDATA)));
if (!pApp)
return DefWindowProc(hWnd, message, wParam, lParam);
}
int wmld, wmEvent;
PAINTSTRUCT ps;
HDC hdc;
switch (message)
{
case WM_COMMAND:
{
int wmId = LOWORD(wParam);
// Parse the menu selections:
switch (wmId)
{
case IDM_ABOUT:
DialogBox(NULL, MAKEINTRESOURCE(IDD_ABOUTBOX), hWnd, pApp->About);
break;
case IDM_EXIT:
DestroyWindow(hWnd);
break;
default:
return DefWindowProc(hWnd, message, wParam, lParam);
}
}
break;
case WM_PAINT:
{
hdc = BeginPaint(hWnd, &ps);
pApp->OnRender(hWnd);
EndPaint(hWnd, &ps);
break;
}
break;
case WM_DESTROY:
PostQuitMessage(0);
break;
default:
return DefWindowProc(hWnd, message, wParam, lParam);
}
return 0;
}
// Message handler for about box.
INT_PTR CALLBACK App::About(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam)
{
UNREFERENCED_PARAMETER(lParam);
switch (message)
{
case WM_INITDIALOG:
return (INT_PTR)TRUE;
case WM_COMMAND:
if (LOWORD(wParam) == IDOK || LOWORD(wParam) == IDCANCEL)
{
EndDialog(hDlg, LOWORD(wParam));
return (INT_PTR)TRUE;
}
break;
}
return (INT_PTR)FALSE;
}
HRESULT App::CreateDeviceIndependentResources()
{
HRESULT hr;
// Create a Direct2D factory
hr = D2D1CreateFactory(D2D1_FACTORY_TYPE_SINGLE_THREADED, &m_pD2DFactory);
if (SUCCEEDED(hr))
{
// Create an ellipse geometry
const D2D1_ELLIPSE ellipse = D2D1::Ellipse(D2D1::Point2F(105.0f, 105.0f), 25.0f, 25.0f);
hr = m_pD2DFactory->CreateEllipseGeometry(ellipse, &m_pEllipseGeometry);
}
return hr;
}
HRESULT App::CreateDeviceResources(HWND hwnd)
{
//Notice that this causes HERE to be printed out, indicating that m_pRenderTarget != NULL
if (m_pRenderTarget != NULL)
OutputDebugStringA("\nHERE\n");
else
OutputDebugStringA("\nTHERE\n");
HRESULT hr = S_OK;
if (!m_pRenderTarget) {
RECT rc;
GetClientRect(hwnd, &rc);
D2D1_SIZE_U size = D2D1::SizeU(rc.right - rc.left, rc.bottom - rc.top);
// Create a Direct2D render target
hr = m_pD2DFactory->CreateHwndRenderTarget( D2D1::RenderTargetProperties(), D2D1::HwndRenderTargetProperties(hwnd, size), &m_pRenderTarget );
if (SUCCEEDED(hr))
{ // Create a black brush
hr = m_pRenderTarget->CreateSolidColorBrush( D2D1::ColorF(D2D1::ColorF::Black), &m_pBlackBrush );
}
}
return hr;
}
HRESULT App::OnRender(HWND hwnd)
{
HRESULT hr;
hr = CreateDeviceResources(hwnd);
if (SUCCEEDED(hr))
{
if (!(m_pRenderTarget->CheckWindowState() & D2D1_WINDOW_STATE_OCCLUDED))
{
m_pRenderTarget->BeginDraw();
m_pRenderTarget->Clear(D2D1::ColorF(D2D1::ColorF::White));
m_pRenderTarget->FillGeometry(m_pEllipseGeometry, m_pBlackBrush);
hr = m_pRenderTarget->EndDraw();
if (hr == D2DERR_RECREATE_TARGET)
{
hr = S_OK;
m_pRenderTarget->Release();
m_pRenderTarget = NULL;
m_pBlackBrush->Release();
m_pBlackBrush = NULL;
}
}
}
return hr;
}
I apologize for the amount of code I am offering. I am completely confused about the problem as I had thought that I was copying exactly what was written in the docs. I suppose I must have made an error in transcription. Thank you for any help you can offer.
回答1:
The reason is that you wrote an extra parameter when using the CreateWindow function, which caused hInstance to be acquired by lpCreateParams, which caused an access exception.
Just modify the code as follows:
hWnd = CreateWindow(szWindowClass, szTitle, WS_OVERLAPPEDWINDOW, CW_USEDEFAULT,
CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, NULL, NULL, GetModuleHandle(NULL), this);
And it works for me:
回答2:
This kind of issue screams one of the following:
- your class pointer is invalid through being destroyed, uninitialized, or otherwise;
- you have stack or heap corruption e.g. buffer overflow or other undefined behavior.
Now, let's look at the strings appearing in your class, which are candidates for buffer overflow. Nope, it looks like you're initializing those fine.
Okay, more static analysis. Work backwards from where the issue happens.
- who called
CreateDeviceResources? It wasOnRender - who called
OnRender? It was theWM_PAINThandler. - that call is very simple:
pApp->OnRender(hWnd); - so, is
pAppvalid? Where is that initialized? - it's stored in the window long pointer -- when is that stored?
And this leads me to this line:
::SetWindowLongPtrW(hWnd, GWLP_USERDATA, PtrToUlong(pApp));
Okay, what's fishy about that? Well, PtrToULong is not a function (or macro) I've ever used, but based on its name, I'm immediately suspicious because I'm used to programming in 64-bits and I know that the type ULONG in Windows API is 32-bit.
So, I go and check the docs, and sure enough I find that's the case. Not only this, but I find several writings about how this is actually a common culprit for breaking programs when porting to 64-bit.
Note that you could have arrived here already if you had attached your debugger, which would break when the access violation occurs. And then you could have looked at the call stack. You could then check the other contents of your pApp class and probably see the entire thing is corrupt.
At this point, you just go "hey I know this is sketchy", and you change the line to something like:
::SetWindowLongPtrW(hWnd, GWLP_USERDATA, reinterpret_cast<LONG_PTR>(pApp));
Now you compile your program and try again. I'm willing to bet that it works. So much so, that I've written this entire answer based on that bet.
Another way you could have arrived at this particular path of investigation would have been to print out the value of this in your App constructor, and check it again in OnRender when you saw things go wonky.
来源:https://stackoverflow.com/questions/64997923/read-access-violation-using-m-prendertarget-with-winapi-due-to-non-null-pointer