Handle object in c++
I开发者_Go百科've been told that a handle is a sort of "void" pointer. But what exactly does "void pointer" mean and what is its purpose. Also, what does "somehandle = GetStdHandle(STD_INPUT_HANDLE);
do?
A handle in the general sense is an opaque value that uniquely identifies an object. In this context, "opaque" means that the entity distributing the handle (e.g. the window manager) knows how handles map to objects but the entities which use the handle (e.g. your code) do not.
This is done so that they cannot get at the real object unless the provider is involved, which allows the provider to be sure that noone is messing with the objects it owns behind its back.
Since it's very practical, handles have traditionally been integer types or void*
because using primitives is much easier in C than anything else. In particular, a lot of functions in the Win32 API accept or return handles (which are #define
d with various names: HANDLE
, HKEY
, many others). All of these types map to void*
.
Update:
To answer the second question (although it might be better asked and answered on its own):
GetStdHandle(STD_INPUT_HANDLE)
returns a handle to the standard input device. You can use this handle to read from your process's standard input.
A HANDLE
isn't necessarily a pointer or a double pointer, it may be an index in an OS table as well as anything else. It's defined for convenience as a void *
because often is used actually as a pointer, and because in C void *
is a type on which you can't perform almost any operation.
The key point is that you must think at it as some opaque token that represents a resource managed by the OS; passing it to the appropriate functions you tell them to operate on such object. Because it's "opaque", you shouldn't change it or try to dereference it: just use it with functions that can work with it.
A HANDLE
is a pointer to a pointer, it's pretty much as simple as that.
So to get the pointer to the data, you'd have to dereference it first.
GetStdHandle(STD_INPUT_HANDLE)
will return the handle to the stdin stream - standard input. That's either the console or a file/stream if you invoke from the command prompt with a '<' character.
A Windows HANDLE
is effectively an index into an array of void pointers, plus a few other things. A void pointer (void*
) is the pointer that points to an unknown type and should be avoided at all costs in C++- however the Windows API is C-compatible and uses it to avoid having to expose Windows internal types.
GetStdHandle(STD_INPUT_HANDLE)
means, get the HANDLE
associated to the Standard output stream.
精彩评论