4

This is a kind of follow-up to this question. Windows SDK features HANDLE datatype that is defined in WinNT.h as follows:

typedef void *HANDLE;

This datatype is used to represent handles. Technically a handle is not a pointer - it's magic value that can only be used with Win32 functions. Yet it is declared to be represented with a datatype that is a void* typedef.

If I want to output the handle hex value with the following code:

HANDLE handle = ...;
printf("%p", handle);

will it be legal?

Community
  • 1
  • 1
sharptooth
  • 167,383
  • 100
  • 513
  • 979
  • They're actually better documented than just that. As Raymond Chen [points out](http://blogs.msdn.com/b/oldnewthing/archive/2005/01/21/358109.aspx), they're actually `DWORD*` but sometimes you set the low bit. – MSalters Jul 30 '12 at 11:22

2 Answers2

5

Yes it's fine, for two reasons. Firstly it is actually a pointer (a pointer to void), and secondly %p doesn't magically check that the value on the stack is a pointer - it just grabs the next pointer-sized value and prints it out.

Jonathan Potter
  • 36,172
  • 4
  • 64
  • 79
  • The second part is actually untrue, as the answers to the previous question show. E.g. Raymond Chen's example of the 68000, which grabs an `%p` argument from an address register, but `%u` from an integer register. – MSalters Jul 30 '12 at 11:15
  • I didn't realise the Windows SDK was available for the 68000. On Windows at least, { int a = 0x12345678; printf("%p\n", a); } prints 12345678 just fine (in a 32 bit program of course). – Jonathan Potter Jul 30 '12 at 18:50
  • Then have a look at the pecularties of the Xenon processor in the XBox 360. The x86 with its lack of registers is real the exception. – MSalters Jul 31 '12 at 07:01
1
HANDLE handle = ...;
printf("%p", handle);

Will this be legal? This would be correct because this will work. At the same time there is no "legal way" of printing handles. Microsoft is free to change the definition of handle to something different, like:

struct HANDLE { DWORD dummy; };

I even remember this definition was present in some older books.

32 bit NT has 2 types of handles: 32 bit and 64 bit. So, it is still necessary to check the handle that you have.

Kirill Kobelev
  • 10,252
  • 6
  • 30
  • 51