Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does MAKEINTRESOURCE() work?

The macro is defined as:

#define MAKEINTRESOURCEA(i) ((LPSTR)((ULONG_PTR)((WORD)(i))))
#define MAKEINTRESOURCEW(i) ((LPWSTR)((ULONG_PTR)((WORD)(i))))

How come this can be used to indicate either a resource ID (a 16-bit unsigned int) or its name (a pointer to an array of char)? Doesn't this effectively limit the address space (on a 32-bit system) to 16-bit? Otherwise how does the system know whether I'm using an ID or a name?

like image 632
twf Avatar asked Aug 31 '10 15:08

twf


2 Answers

This works because Windows doesn't allow mapping pages for the first 64 KB of the address space. To catch null pointer references. But I think also to catch pointer bugs in programs that were converted from the 16-bit version of Windows.

A side-effect is that this allows to reliably distinguish resource IDs packed into a pointer value since they'll always point to non-mappable memory.

like image 108
Hans Passant Avatar answered Oct 17 '22 23:10

Hans Passant


MAKEINTRESOURCE macro just makes casting between numeric parameter and string pointer. The resulting string pointer is invalid and cannot be dereferenced as resource name. However, resource handling API detect such pointers by their absolute value and treat them as resource ID and not resource name. Since C-style API doesn't support overloading, they cannot define two functions like:

HICON LoadIcon(HINSTANCE hInstance,LPCTSTR lpIconName);
HICON LoadIcon(HINSTANCE hInstance,UINT resourceId);

So, API developers decided to use the same function for both cases, providing MAKEINTRESOURCE macro for API users. I believe that two different functions could look better:

HICON LoadIconByName(HINSTANCE hInstance,LPCTSTR lpIconName);
HICON LoadIconById(HINSTANCE hInstance,UINT resourceId);

But this is not the way Windows API is implemented. Valid resource ID is always less than minimal possible pointer value. Resource name parameter is passed to API without this macro, and its value is not restricted.

like image 40
Alex F Avatar answered Oct 17 '22 22:10

Alex F