sharptooth
sharptooth

Reputation: 170509

Can I output a Windows handle using %p specifier?

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?

Upvotes: 4

Views: 15052

Answers (2)

Kirill Kobelev
Kirill Kobelev

Reputation: 10557

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.

Upvotes: 1

Jonathan Potter
Jonathan Potter

Reputation: 37192

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.

Upvotes: 5

Related Questions