Handle object in c++ - c++

I'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 #defined 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.

Related

What are opaque identifiers with regards to handles?

I have read this article and I encountered the following
A resource handle can be an opaque identifier, in which case it is
often an integer number (often an array index in an array or "table"
that is used to manage that type of resource), or it can be a pointer
that allows access to further information.
So a handle is either an opaque identifier or a pointer that allows access to further information. But from what I understand, these specific pointers are opaque pointers, so what exactly is the difference between these pointers ,which are opaque pointer, and opaque identifiers?
One of the literal meanings of "opaque" is "not transparent".
In computer science, an opaque identifier or a handle is one that doesn't expose its inner details. This means we can only access information from it by using some defined interface, and can't otherwise access information about its value (if any) or internal structure.
As an example, a FILE in the C standard library (and available in C++ through <cstdio>) is an opaque type. We don't know if it is a data structure, an integer, or anything else. All we know is that a set of functions, like fopen() return a pointer to one (i.e. a FILE *) and other functions (fclose(), fprintf(), ....) accept a FILE * as an argument. If we have a FILE *, we can't reliably do anything with it (e.g. actually write to a file) unless we use those functions.
The advantage of that is it allows different implementations to use different ways of representing a file. As long as our code uses the supplied functions, we don't have to worry about the internal workings of a FILE, or of I/O functions. Compiler vendors (or implementers of the standard library) worry about getting the internal details right. We simply use the opaque type FILE, and pointers to it, and stick to using standard functions, and our code works with all implementations (compilers, standard library versions, host systems)
An opaque identifier can be of any type. It can be an integer, a pointer, even a pointer to a pointer, or a data structure. Integers and pointers are common choices, but not the only ones. The key is only using a defined set of operations (i.e. a specific interface) to interact with those identifiers, without getting our hands dirty by playing with internal details.
A handle is said to be "opaque" when client code doesn't know how to see what it references. It's simply some identifier that can be used to identify something. Often it will be a pointer to an incomplete type that's only defined within a library and who's definition isn't visible to client code. Or it could just be an integer that references some element in some data structure. The important thing is that the client doesn't know or care what the handle is. The client only cares that it uniquely identifies some resource.
Consider the following interface:
widget_handle create_widget();
void do_a_thing(widget_handle);
void destroy_widget(widget_handle);
Here, it doesn't actually matter to the calling code what a widget_handle is, how the library actually stores widgets, or how the library actually uses a widget_handle to find a particular widget. It could be a pointer to a widget, or it could be an index into some global array of widgets. The caller doesn't care. All that matters is that it somehow identifies a widget.
One possible difference is that an integer handle can have "special" values, while pointer handle cannot.
For example, the file descriptors 0,1,2 are stdin, stdout, stderr. This would be harder to pull off if you have a pointer for a handle.
You really you shouldn't care. They could be everything.
Suppose you buy a ticket from person A for an event. You must give this ticket to person B to access the event.
The nature of the ticket is irrelevant to you, it could be:
a paper ticket,
an alphanumerical code,
a barcode,
a QR-Code,
a photo,
a badge,
whatever.
You don't care. Only A and B use the ticket for its nature, you are just carrying it around. Only B knows how to verify the validity and only A know how to issue a correct ticket.
An opaque pointer could be a memory location directly, while an integer could be an offset of a base memory address in a table but how is that relevant to you, client of the opaque handle?
In classic Mac OS memory management, handles were doubly indirected pointers. The handle pointed to a "master pointer" which was the address of the actual data. This allowed moving the actual storage of the object in memory. When a block was moved, its master pointer would be updated by the memory manager.
In order to use the data the handle ultimately referenced, the handle had to be locked, which would prevent it being moved. (There was little concurrency in the system so unless one was calling the operating system or libraries which might, one could also rely on memory not getting moved. Doing so was somewhat perilous however as code often evolved to call something that could move memory inside a place where that was not expected.)
In this design, the handle is a pointer but it is not an opaque type. A generic handle is a void ** in C, but often one had a typed handle. If you look here you'll find lots of handle types that are more concrete. E.g. StringHandle.

Handle , Void Pointer , Objects in C++

So I was reading the article on Handle in C and realized that we implement handles as void pointers so "whatever" Object/data type we get we can cast the void pointer to that kind of Object/data and get its value. So I have basically two concerns :
1.If lets say in following example taken from Handle in C
typedef void* HANDLE;
int doSomething(HANDLE s, int a, int b) {
Something* something = reinterpret_cast<Something*>(s);
return something->doit(a, b);
}
If we pass the value to the function dosomething(21,2,2), does that mean the value HANDLE points to is 21, if yes how does any object when we type cast it to that object, will it be able to use it, like in this example, so in otherwords where does pointer to the object Something, something, will store the value 21.
2.Secondly the link also says "So in your code you just pass HANDLE around as an opaque value" what does it actually mean? Why do we "pass handle around"? If someone can give more convincing example of handles that uses objects that will be great!
1.: A handle is an identifier for an object. Since "21" is no object, but simply a number, your function call is invalid. Your code will only work if 's' really points to a struct of type Something. Simply spoken, a handle is nothing than a pointer is nothing than a memory address, thus "21" would be interpreted as a memory address and will crash your program if you try to write to it
2.: "Opaque value" means that no developer that uses your code can't take any assumptions about the inner structure of an object the handle identifies. This is an advantage over a pointer to a struct, where a developer can look at the structure and take some assumptions that will not be true anymore after you changed your code. "Pass around" simply means: assigning it and using it as a function call parameter, like in:
HANDLE s = CreateAnObject();
DoSomethingWithObject( s );
HANDLE t = s;
etc.
By the way: In real code, you should give handles to your objects different names, like EMPLOYEE_HANDLE, ORDER_HANDLE etc.
A typical example of a handle are window handles in Windows. They identify windows, without giving you any information about how a "Window" memory structure in the operating system is built, therefore Microsoft was able to change this inner structure without the risk of breaking other developer's code with changes to the "Window" structure.
I didn't realize there was one defacto article on HANDLEs or a defacto way to implement them. They are usually a windows construct and can be implemented any way some developer from 1985 decided to implement them.
It really has as much meaning as "thingy", or rather "thingy that can be used to get a resource"
Do not get into the habit of creating your own "handle" and certainly do not try to mimic code idioms from 1985. Void pointers, reinterpret_casts, and HANDLE are all things that you should avoid at all costs if possible.
The only time you should have to deal with "HANDLE" is when using the Windows API in which case the documentation will tell you what to do with it.
In modern C++, if you want to pass objects around, use references, pointers, and smart pointers(including unique_ptr, shared_ptr, weak_ptr) and study up on which scenarios call for which.
If we pass the value to the function dosomething(21,2,2), does that mean the value HANDLE points to is 21,
No. It just means that value of the void* is 21. If you treat 21 as the value of a pointer to an object of type Something, it will most likely lead to undefined behavior.
2.Secondly the link also says "So in your code you just pass HANDLE around as an opaque value" what does it actually mean? Why do we "pass handle around"? If someone can give more convincing example of handles that uses objects that will be great!
A handle is opaque in the sense that you cannot see anything through it. If a handle is represented by a void*, you can't see anything about the object since a void* cannot be dereferenced. If a handle is represented by an int (as an index to some array defined elsewhere in your code), you can't look at the value of the handle and make any sense of what the corresponding object represents.
The only way to make sense of a handle is to convert it a pointer or a reference using a method that is appropriate for the handle type.
In the case where a handle is represented by a void*, the code you have posted illustrates how to extract a pointer to a concrete object and make sense of the object.
In the case where a handle is represented by an int, you may see something along the lines of:
int doSomething(HANDLE s, int a, int b) {
// If the value of s is 3, something will be a reference
// to the fourth object in the array arrayOfSomethingObjects.
Something& something = arrayOfSomethingObjects[s];
return something.doit(a, b);
}

Check if opaque C handle is OK

I have a C++ API with a C wrapper. A C client can get a handle to an underlying C++ object and then use that to get other information about the object, e.g.
PersonHandle handle = createPerson("NisseIHult");
char* name = getPersonName(handle); //Get person takes a void* pointer
In the code above, the handle is casted to a C++ Person class object.
Question is, how can I check inside getPersonName that the argument, handle, is a valid handle? For example, if a client does this:
char* name = getPersonName(1234);
it will cause an access violation inside getPersonName. I need a way to check and validate the handle, and in the case above, return NULL?
Since handles are pointers to C++ objects, there is no reliable way to check their validity without triggering some undefined behavior.
I have seen two solutions to this problem:
Make handles integers for full control - rather than giving out pointers, keep pointers internally - say, in an unordered map from int to a pointer, along with some metadata, and give users integers to use as handles. This introduces an additional hash lookup in the process of accessing a person, but you can make this perfectly reliable, because all ints are under your control. For example, if you give out handles to objects of different types, you could produce a detailed error message, e.g. "a handle to a Horse object has been used where a Person handle is required". This solution has an additional advantage that you don't have dangling references: a user can pass a handle that you have invalidated, but you can quickly tell that the object is deleted.
Derive all objects to which you give handles from a common base class, and put a "magic number" into the first member of that class - A "magic number" is a bit pattern that you put, say, in an int, and set it in each Person object. After the cast you can check if (personFromHandle->magic != 0xBEEFBEEF) ... to see if the pattern is there. This solution is common, but I would recommend against it, because it has undefined behavior when an invalid handle is passed. It's not OK to use it if the operation is to continue after a failed attempt to use a handle. This solution would also break if passed a reference to a deallocated object.
Similar to the first part of the answer above, put the address of every object you hand out into a std::set (or similar container) and test for existence in the set before casting.

How are Handles managed properly?

This is a very basic question about the correct use of a HANDLE. Given the following code (it is not a particular source file):
typedef void* HANDLE;
HANDLE myHandle;
myHandle = SomeObject;
//...some elaborate code...//
First question: Is myHandle now located on the Stack or Heap? Since a Handle can be a pointer as well as just an index I am not quite sure about that.
At the point myHandle is out of scope it is removed (at least I think so). But in case it is a class member it remains visible until the owning object was deleted. So second question:
If I want to avoid any further access to myHandle, is it good practice to do
myHandle = 0; // I do not need this handle anymore
Would I run into a conflict with memory management now, or any other restrictions regarding managed code? Are there other options to state that this handle should not be used anymore similar to pointers:
mypointer = NULL;
EDIT: I was talking about garbage collection in first place which is obviously not included in c++. This is a part of managed extensions. Thanks for helping me out with this fatal error!
You are probably a Java programmer from the assumptions that you make.
The variable myHandle is indeed allocated on the stack, and it is removed when it goes out of scope, although not by a garbage collector (no such thing exists in C++).
However, this does not free the handle (myHandle is just a variable that holds some opaque numeric value, the actual handle is owned by the OS -- so its lifetime is not identical to the lifetime of any arbitrary variable holding that value). You must do this yourself using the appropriate API function (for most things that are a HANDLE, this is CLoseHandle), preferrably with a "handle holder" class so it is exception-safe.
A simple implementation of such a handle holder could look like this:
class AutoHandle
{
HANDLE handle;
public:
AutoHandle(HANDLE in) : handle(in) {}
~AutoHandle() { CloseHandle(handle); }
};
That way, you assign to a AutoHandle variable when opening a resource, and when it goes out of scope, the handle is closed. You cannot forget to do it, and it will even work if an exception occurs.
As you have not specified what HANDLEs you are talking about, I assume Windows handles.
A HANDLE is an opaque data-type (mostly represents a number the OS can work with) and should be treated only by system-functions such as CreateFile or CloseHandle.
You should never set a HANDLE to 0 by yourself as you are losing the associated resource.
See CloseHandle, CreateFile(especially the Return Value), and Windows Data Types.
From Wikipedia
In computer programming, a handle is an abstract reference to a resource. Handles are used when application software references blocks of memory or objects managed by another system, such as a database or an operating system.
While a pointer literally contains the address of the item to which it refers, a handle is an abstraction of a reference which is managed externally; its opacity allows the referent to be relocated in memory by the system without invalidating the handle, which is impossible with pointers. The extra layer of indirection also increases the control the managing system has over operations performed on the referent. Typically the handle is an index or a pointer into a global array of tombstones.
And C++ does not have a garbage collection by the Standard, this is why you need to delete newed objects yourself, but not handles given by the system!
Usually prefer to use delete before put a pointer to NULL.
But for a HANDLER don't put it to NULL yourself !

What is a handle in C++?

I have been told that a handle is sort of a pointer, but not, and that it allows you to keep a reference to an object, rather than the object itself. What is a more elaborate explanation?
A handle can be anything from an integer index to a pointer to a resource in kernel space. The idea is that they provide an abstraction of a resource, so you don't need to know much about the resource itself to use it.
For instance, the HWND in the Win32 API is a handle for a Window. By itself it's useless: you can't glean any information from it. But pass it to the right API functions, and you can perform a wealth of different tricks with it. Internally you can think of the HWND as just an index into the GUI's table of windows (which may not necessarily be how it's implemented, but it makes the magic make sense).
EDIT: Not 100% certain what specifically you were asking in your question. This is mainly talking about pure C/C++.
A handle is a pointer or index with no visible type attached to it. Usually you see something like:
typedef void* HANDLE;
HANDLE myHandleToSomething = CreateSomething();
So in your code you just pass HANDLE around as an opaque value.
In the code that uses the object, it casts the pointer to a real structure type and uses it:
int doSomething(HANDLE s, int a, int b) {
Something* something = reinterpret_cast<Something*>(s);
return something->doit(a, b);
}
Or it uses it as an index to an array/vector:
int doSomething(HANDLE s, int a, int b) {
int index = (int)s;
try {
Something& something = vecSomething[index];
return something.doit(a, b);
} catch (boundscheck& e) {
throw SomethingException(INVALID_HANDLE);
}
}
A handle is a sort of pointer in that it is typically a way of referencing some entity.
It would be more accurate to say that a pointer is one type of handle, but not all handles are pointers.
For example, a handle may also be some index into an in memory table, which corresponds to an entry that itself contains a pointer to some object.
The key thing is that when you have a "handle", you neither know nor care how that handle actually ends up identifying the thing that it identifies, all you need to know is that it does.
It should also be obvious that there is no single answer to "what exactly is a handle", because handles to different things, even in the same system, may be implemented in different ways "under the hood". But you shouldn't need to be concerned with those differences.
In C++/CLI, a handle is a pointer to an object located on the GC heap. Creating an object on the (unmanaged) C++ heap is achieved using new and the result of a new expression is a "normal" pointer. A managed object is allocated on the GC (managed) heap with a gcnew expression. The result will be a handle. You can't do pointer arithmetic on handles. You don't free handles. The GC will take care of them. Also, the GC is free to relocate objects on the managed heap and update the handles to point to the new locations while the program is running.
This appears in the context of the Handle-Body-Idiom, also called Pimpl idiom. It allows one to keep the ABI (binary interface) of a library the same, by keeping actual data into another class object, which is merely referenced by a pointer held in an "handle" object, consisting of functions that delegate to that class "Body".
It's also useful to enable constant time and exception safe swap of two objects. For this, merely the pointer pointing to the body object has to be swapped.
A handle is whatever you want it to be.
A handle can be a unsigned integer used in some lookup table.
A handle can be a pointer to, or into, a larger set of data.
It depends on how the code that uses the handle behaves. That determines the handle type.
The reason the term 'handle' is used is what is important. That indicates them as an identification or access type of object. Meaning, to the programmer, they represent a 'key' or access to something.
HANDLE hnd; is the same as void * ptr;
HANDLE is a typedef defined in the winnt.h file in Visual Studio (Windows):
typedef void *HANDLE;
Read more about HANDLE
Pointer is a special case of handle. The benefit of a pointer is that it identifies an object directly in memory, for the price of the object becoming non-relocatable. Handles abstract the location of an object in memory away, but require additional context to access it. For example, with handle defined as an array index, we need an array base pointer to calculate the address of an item. Sometimes the context is implicit at call site, e.g. when the object pool is global. That allows optimizing the size of a handle and use, e.g. 16-bit int instead of a 64-bit pointer.