Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Problems Using RegisterClassEx

In my Win32 C++ DLL I find that if I try to use RegisterClassEx this way it works just fine:

WNDCLASSEX wx = {};
wx.cbSize = sizeof(WNDCLASSEX);
wx.lpfnWndProc = (WNDPROC)WndProc;        // function which will handle messages
wx.hInstance = GetCurrentModule();
wx.lpszClassName = pClassName;
atomRet = RegisterClassEx( &wx );

However, when I try to use RegisterClassEx this way, it fails, atomRet is set to zero, and the exception text simply states, "The parameter is incorrect."

WNDCLASSEX * _pWndClassEx;
_pWndClassEx = (WNDCLASSEX *)malloc( sizeof(WNDCLASSEX) );
_pWndClassEx->cbSize = sizeof(WNDCLASSEX);
_pWndClassEx->lpfnWndProc = (WNDPROC)WndProc;        // function which will handle messages
_pWndClassEx->hInstance = GetCurrentModule();
_pWndClassEx->lpszClassName = pClassName;
atomRet = RegisterClassEx( _pWndClassEx );

I noticed in the MSDN documentation for RegisterClassEx that it is defined as follows:

ATOM WINAPI RegisterClassEx(
  __in  const WNDCLASSEX *lpwcx
);

Does this mean that lpwcx must be pointing to statically allocated memory? That is, it cannot be pointing to dynamically-allocated memory (allocated using malloc)? Thank you.

like image 466
Jim Fell Avatar asked Jun 22 '26 04:06

Jim Fell


2 Answers

When you do:

WNDCLASSEX * _pWndClassEx;

you aren't allocating any memory for the structure. You need to do something like:

WNDCLASSEX * _pWndClassEx = new WNDCLASSEX;

before you can assign to the members in the structure.

However, I don't see any reason for dynamically allocating a WNDCLASSEX structure, because you really don't need it once you call RegisterClassEx.

like image 125
casablanca Avatar answered Jun 24 '26 20:06

casablanca


In your first example,

WNDCLASSEX wx = {};

the declaration of wx is also zero-initializing all the fields.

In your second example, you don't show how _pWndClassEx is being initialized, but you mention getting memory for the structure using malloc(). To be equivalent to the first example, you'll need to clear out the memory returned from malloc():

memset( _pWndClassEx, 0, sizeof(*_pWndClassEx));

Otherwise the fields that you don't explicitly assigned values to will have indeterminate values (and in particular in a debug build, the memory returned from malloc() will be set to 0xcd if I remember right, so any pointers and handles in the WNDCLASSEX struct will have invalid values).

like image 36
Michael Burr Avatar answered Jun 24 '26 19:06

Michael Burr