I am writing multi-thread socket chat in C++Builder 2009.
It is almost complete in accordance with what I need to do but I have a little problem. I need to pass the TMemo* pointer into CreateThread WinAPI function which upcasts it to void*.
I tryed this way:
HANDLE xxx = MemoChat->Handle; hNetThread = CreateThread(NULL, 0, NetThread, xxx, 0, &dwNetThreadId); //...
and then, in NetThread function,
TMemo* MyMemo((HANDLE)lpParam); TMemo* MyMemo((TMemo*)lpParam);
but it didn`t work:(
The question is how I can really downcast it correctly so I can use my Memo Component in this new thread?
Call:
What is happening here is that any pointer you pass as the third parameter is being auto converted into a void pointer (or in WinTerms LPVOID). That’s fine it does not change it it just loses the type information as the system does not know anything about your object.
The new Thread Start point:
Once your thread start method is called. Just convert the void pointer back into the correct type and you should be able to start using it again.
Just to clear up other misconceptions.
A HANDLE is a pointer.
And you could have passed it as the parameter to the NetThread().
A HANDLE is a pointer to pointer under system control which points at the object you are using. So why the double indirection. It allows the system to move the object (and update its pointer) without finding all owners of the object. The owners all have handles that point at the pointer that was just updated.
It is an old fashioned computer science concept that is used infrequently in modern computers because of the OS/Hardware ability to swap main memory into secondary storage. but for certain resource they are still useful. Nowadays when handles are required they are hidden inside objects away from the user.