Handle , Void Pointer , Objects in C++ - 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);
}

Related

How windows APIs accept strings

I have to admit this has always confused me how certain windows API accept strings. Take for example SetWindowText(). Now any function which takes a pointer to anything typically means it doesn't store that object but merely use the pointer that is passed. Therefore the caller has the responsibility to make sure the object passed to it exist for whenever it may be needed. Now what would you expect the final message that will be printed out below?
TCHAR * label = new TCHAR[50]();
_tcscpy( label, _T("allocated string") );
m_wndStaticLabel.SetWindowText( label );
_tcscpy( label, _T("string has changed") );
Theoretically I would expect it to print "string has changed" but it prints "allocated string". Similarly:
CString label = _T("CString Label");
m_wndStaticLabel.SetWindowText( label );
In this case a pointer of a local variable 'label` is being passed to it but still no problem. The control always prints the right string even though it received pointer of string allocated on stack.
This implies that the control actually allocate its own memory and assign that to the control instead of the pointer we are passing but this fact is never documented. Isn't this a little misleading? When I am passing a pointer to a function, one thing I immediately remind myself is I shouldn't be destroying it until the function returns but it is not the case in this case and it is not documented either.
So my question ultimately is this simply lack of documentation or there is something else to it when we passing a pointer to an object but it essentially behaves like we have passed object by value?
Remember that the Windows API is based on C conventions. This means that the only way to pass a string is as a pointer to the first character. None of the functions accept a CString or std::wstring for example, except by implicit conversion to a const wchar_t *.
You are right to be concerned about whether a copy of the pointer is retained by the control, but rest assured that it doesn't. The documentation doesn't mention this, it's assumed by default - if the pointer was retained, there would be a note about it. You'll find that some handles are documented in this manner.
I think all windows API functions that take pointers will only use the pointers while running, but never store them (except for special documented cases). When the data is needed later, a copy is made.
The problem if a function would store the pointers would be that the system is taking ownership of the objects, and thus would be responsible for freeing them. But then the functions would need to know how the objects were allocated - there are many possibilities.
I usually also adhere to this principle in my own functions.
In C++, arrays decay to pointers when passed as function arguments, so the prototype is exactly as it should be -- a pointer to a TCHAR. Otherwise, how do you suggest the function prototype for SetWindowText() be written?
In addition, look at your code sample. You overlooked the _tcscpy() function and concentrated solely on SetWindowText(). Given your reasoning, how is _tcscpy() supposed to behave when given a TCHAR*?

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.

Handle object in 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.

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.

check if X is derived of Y via typeid

i need to convert pointers to long (SendMessage())
and i want to safely check if the variable is correct on the otherside. So i was thinking of doing dynamic_cast but that wont work on classes that are not virtual. Then i thought of doing typeid but that will work until i pass a derived var as its base.
Is there any way to check if the pointer is what i am expecting during runtime?
Is there a way i can use typeid to see if a pointer is a type derived from a particular base?
Your reference to SendMessage() makes i sounds like MS Windows is your platform and then the Rules for Using Pointers (Windows) is recommended reading. It details the PtrToLong and PtrToUlong functions and other things Microsoft provide for you in situations like this.
If all you have is a long, then there's not really much you can do. There is no general way to determine whether an arbitrary number represents a valid memory address. And even if you know it's a valid memory address, there is no way to determine the type of the thing the pointer points to. If you can't be sure of the real type of the thing before its address was cast to long, then you can't be sure that it's going to be safe to cast the long to whatever type you plan on casting it to.
You'll just have to trust that the sender of the message has sent you a valid value. The best you can do is to take some precautions to reduce the consequences to your own program when it receives a bogus value.
You cannot use typeid. It will result in an Access Violation if you get garbage instead of a valid pointer, so your check is nonsensical.
What you should do, is wrap your SendMessage and the code which processes the message into a single type-safe interface. This way you will be unable to pass unexpected things to SendMessage, and will not need any checks on receiving side.
C++ type system works at compile time. Once you cast a pointer to a long, you loose all type information. A long is just so much bits in memory; there is no way you can identify that it was pointing to an object.
PTLib ( http://sourceforge.net/projects/opalvoip/ ) uses a PCLASSINFO macro to define relations between classes. This provides functions like IsDescendant and GetClass.
You could probably implement something similar.
dynamic_cast works by checking the signature of the virtual method table. If you have no virtual methods, you have no VMT, so as you say dynamic_cast won't work. However, if you have no VMT, you have absolutely NO knowledge about the object being pointed to.
Your best bet is to require that pointers are to classes with at least one virtual method, even if it's a dummy. Dynamic cast will work then.
I don't understand yet what your question is about.
If it is whether or not you can be sure that casting to a long and back will yield the same value, view Safely checking the type of a variable
Given the "Rules for using Pointers" MS-Site the other Answerer linked to, the right type to cast to is UINT_PTR. So you do UINT_PTR v = reinterpret_cast<UINT_PTR>(ptr); to cast to a integral type, and do the reverse to cast it back to the pointer again. The C++ Standard guarantees that the original value is restored. (see the link i gave above for my explanation of that). That Microsoft site by the way also says that WPARAM and LPARAM change their size depending on the platform. So you could just use that variable v and SendMessage it.
If it is how you can check on the other side whether or not the pointer (converted to some pointer type) points to some object, the answer is you can't. Since you are apparently not sure which pointer type was used to send it, you cannot check on the receiving side what the dynamic type the pointer points to is. If you know the type the pointer had on the sender side, your check would be not required in the first place.
In Windows, MFC provides a method to check if a given pointer is pointing to a valid memory location (this is done by trapping segfault). I do not remember the function name, but it's there. Still, it does not ensure that the contents of the memory pointed to are valid. It may still have invalid VMT and crash your code. Of course, you can trap the segfault yourself (see MS Knowledge Base)
As for checking if something belongs to a type, you must have a base class to start with. If you make the destructor of base class "virtual", all derived classes will have VMTs.
If you must avoid VMT at all costs, you have to have some sort of descriminator that tells you what you're dealing with, such as event type in MS Windows events.