Strange access violation
I have put the windows procedure inside a class as a static member function and I get a pointer to the class containing the function using GetWindowLong(), and everything works fine, like calling member functions trough the pointer and reading variables through the pointer, but when I try to write through the pointer, I get an Access violation writing location... Does anyone know why?
LRESULT CALLBACK Win32Window::WndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
// Get a pointer to the class which this window belongs to
if (msg != WM_CREATE)
w32Window = (Win32Window*)GetWindowLongPtr( hWnd, 0 );
CREATESTRUCT *cs = (CREATESTRUCT*)lParam;
w32Window = (Win32Window*)cs->lpCreateParams;
SetWindowLongPtr(hWnd, GWL_USERDATA, (LONG_PTR) w32Window);
w32Window->aMemberVariable = 0; // this causes a Access violation writing...
return DefWindowProc(hWnd, msg, wParam, lParam);
Please use code tags
If you use 'GWL_USERDATA' to store your c++ class pointer with SetWindowLongPtr then use the same flag to retrieve it with GetWindowLongPtr.
Also note that WM_CREATE is not the first message sent to your window procedure but WM_CREATE is where you first store your c++ class pointer in your window (most use WM_NCCREATE in this respect because it's sent to your window procedure before WM_CREATE). Checking the return value of GetWindowLongPtr is probably a good idea, too, to ensure that the GWL_USERDATA returned is valid.
This is the most recent of a long line of threads on c++ class message handling which may be of some interest to you.
Thanks, using GWL_USERDATA when retrieving the pointer did the trick, I should have thought about that. Code tags will be used in my next post :) .