473,326 Members | 2,813 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,326 software developers and data experts.

Conversion from void* to a point of a class

I want to know to the following in a safe manner (the following code
will be dangerous if p does not contain a pointer to MyClass). I would
like someone to show me a better way (either throw an exception or
return value which I can check if the cast is allowed or not.

void* p;
...
MyClass* pClass = (MyClass*)p;

Thank you very much for your help.

Charles Zhang
Dec 11 '07 #1
7 1299
Hi Charles,
>void* p;
...
MyClass* pClass = (MyClass*)p;
>Thank you very much for your help.

initialize p == NULL, and check whether
p has some valid address pointing at before
you do the casting. NEVER use uninitialized
variables like you wrote here! They will point
to somewhere but not to your allocated memory
for your Class in this example!

something like:

void *p == NULL;

.....
.....
.....

if(p != NULL){
MyClass* pClass = (MyClass*)p;
}else{
//some invalid pointer handling code here
//a messagebox or some console output or whatever
//you like to handle this situation
}
Regards

Kerem

--
-----------------------
Beste Grüsse / Best regards / Votre bien devoue
Kerem Gümrükcü
Microsoft Live Space: http://kerem-g.spaces.live.com/
Latest Open-Source Projects: http://entwicklung.junetz.de
-----------------------
"This reply is provided as is, without warranty express or implied."
Dec 11 '07 #2
(MyClass*) is a C-style cast - in C++, reinterpret_cast, static_cast and
dynamic_cast are preferred. If you are not sure whether p really points
to a MyClass object or rather to an object of a different class, use
dynamic_cast:
http://msdn2.microsoft.com/en-us/lib...cs(VS.80).aspx

--Johannes

Charles Zhang wrote:
I want to know to the following in a safe manner (the following code
will be dangerous if p does not contain a pointer to MyClass). I would
like someone to show me a better way (either throw an exception or
return value which I can check if the cast is allowed or not.

void* p;
...
MyClass* pClass = (MyClass*)p;

Thank you very much for your help.

Charles Zhang

--
Johannes Passing - http://int3.de/
Dec 11 '07 #3
Of course, I will make sure the void pointer is not NULL. However, a
non-null pointer is not necessary a valid pointer of MyClass. Your code
will cause a run time error which could crash the application.

Charles Zhang


Kerem Gümrükcü wrote:
Hi Charles,
>void* p;
...
MyClass* pClass = (MyClass*)p;
>Thank you very much for your help.


initialize p == NULL, and check whether
p has some valid address pointing at before
you do the casting. NEVER use uninitialized
variables like you wrote here! They will point
to somewhere but not to your allocated memory
for your Class in this example!

something like:

void *p == NULL;

....
....
....

if(p != NULL){
MyClass* pClass = (MyClass*)p;
}else{
//some invalid pointer handling code here
//a messagebox or some console output or whatever
//you like to handle this situation
}
Regards

Kerem
Dec 11 '07 #4
Thank you very much. But I actually tried to use dynamic_cast, but I got
an compiler error

void* p = NULL;
....
....
MyClass* pClass = dynamic_cast<MyClass*>(p);

The compiler error is: "invalid expression type for dynamic_cast."

Then I changed the line to:
MyClass* pClass = dynamic_cast<MyClass*>((MyClass*)p);

Now, it compiles. But when p is not an valid pointer to MyClass, now run
time exception was thrown. Which could cause the application to crash.

Charles Zhang

Johannes Passing wrote:
(MyClass*) is a C-style cast - in C++, reinterpret_cast, static_cast and
dynamic_cast are preferred. If you are not sure whether p really points
to a MyClass object or rather to an object of a different class, use
dynamic_cast:
http://msdn2.microsoft.com/en-us/lib...cs(VS.80).aspx

--Johannes

Charles Zhang wrote:
>I want to know to the following in a safe manner (the following code
will be dangerous if p does not contain a pointer to MyClass). I would
like someone to show me a better way (either throw an exception or
return value which I can check if the cast is allowed or not.

void* p;
...
MyClass* pClass = (MyClass*)p;

Thank you very much for your help.

Charles Zhang



Dec 11 '07 #5
dynamic_cast requires a polymorphic type: p must point to an object with at
least one virtual function. Usually this kind of mistake is caught at compile
time, but due to indirection (p) compiler is not be able to do that (and of
course, an invalid pointer is not a polymorphic type).

Regards
--
Cholo Lennon
Bs.As.
ARG
"Charles Zhang" <Ch**********@newsgroups.nospamwrote in message
news:#Z**************@TK2MSFTNGP04.phx.gbl...
Thank you very much. But I actually tried to use dynamic_cast, but I got
an compiler error

void* p = NULL;
...
...
MyClass* pClass = dynamic_cast<MyClass*>(p);

The compiler error is: "invalid expression type for dynamic_cast."

Then I changed the line to:
MyClass* pClass = dynamic_cast<MyClass*>((MyClass*)p);

Now, it compiles. But when p is not an valid pointer to MyClass, now run
time exception was thrown. Which could cause the application to crash.

Charles Zhang

Johannes Passing wrote:
(MyClass*) is a C-style cast - in C++, reinterpret_cast, static_cast and
dynamic_cast are preferred. If you are not sure whether p really points
to a MyClass object or rather to an object of a different class, use
dynamic_cast:
http://msdn2.microsoft.com/en-us/lib...cs(VS.80).aspx

--Johannes

Charles Zhang wrote:
I want to know to the following in a safe manner (the following code
will be dangerous if p does not contain a pointer to MyClass). I would
like someone to show me a better way (either throw an exception or
return value which I can check if the cast is allowed or not.

void* p;
...
MyClass* pClass = (MyClass*)p;

Thank you very much for your help.

Charles Zhang



Dec 11 '07 #6
Well, that is true, dynamic_cast does not work for void-pointers - once
you have converted your MyClass* pointer to a void* you have voluntarily
given up all type information and there is no safe way back.

To convert a void pointer back to MyClass*, you have to use
reinterpret_cast, which in this context is basically the same as the
C-style cast you used initially. There is, of course, no guarantee that
the object returned by reinterpret_cast is indeed a valid object of
MyClass or rather some other garbage.

If possible by any measure, avoid using void-pointers in C++ in the
first place - there is almost always a better way to do it. In C, where
no such thing like RTTI exists, there is one common idiom you could use
in C++ as well if you are urged to use void pointers: To provide at
least a certain degree of sanity checking before using a casted pointer,
include some signature/magic field in the struct/class and check that it
contains the expected value before using it:

void *p = ...
MyClass *my = reinterpret_cast<MyClass*>(p);
if ( my->Signature != MYCLASS_SIGNATURE )
{
// this pointer is invalid
}
else
{
// it is likely the the pointer is valid
}

If you can avoid using void-pointers, do that - it may save you a lot of
trouble.

--Johannes

Charles Zhang wrote:
Thank you very much. But I actually tried to use dynamic_cast, but I got
an compiler error

void* p = NULL;
...
...
MyClass* pClass = dynamic_cast<MyClass*>(p);

The compiler error is: "invalid expression type for dynamic_cast."

Then I changed the line to:
MyClass* pClass = dynamic_cast<MyClass*>((MyClass*)p);

Now, it compiles. But when p is not an valid pointer to MyClass, now run
time exception was thrown. Which could cause the application to crash.

Charles Zhang

Johannes Passing wrote:
>(MyClass*) is a C-style cast - in C++, reinterpret_cast, static_cast
and dynamic_cast are preferred. If you are not sure whether p really
points to a MyClass object or rather to an object of a different
class, use dynamic_cast:
http://msdn2.microsoft.com/en-us/lib...cs(VS.80).aspx

--Johannes

Charles Zhang wrote:
>>I want to know to the following in a safe manner (the following code
will be dangerous if p does not contain a pointer to MyClass). I
would like someone to show me a better way (either throw an exception
or return value which I can check if the cast is allowed or not.

void* p;
...
MyClass* pClass = (MyClass*)p;

Thank you very much for your help.

Charles Zhang




--
Johannes Passing - http://int3.de/
Dec 11 '07 #7
Johannes Passing wrote:
Well, that is true, dynamic_cast does not work for void-pointers - once
you have converted your MyClass* pointer to a void* you have voluntarily
given up all type information and there is no safe way back.

To convert a void pointer back to MyClass*, you have to use
reinterpret_cast, which in this context is basically the same as the
C-style cast you used initially.
Johannes:

You can (and should) use static_cast to convert void pointer. Using
reinterpret_cast is usually an indication that you are doing something
non-portable (which casting a void pointer usually is not).

--
David Wilkinson
Visual C++ MVP
Dec 12 '07 #8

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
by: Thomas Matthews | last post by:
Hi, I'm working with Borland C++ Builder 6.2. My project uses the std::string class. However, Borland in its infinite wisdom has its own string class, AnsiString. To make my life easier, I...
3
by: Siemel Naran | last post by:
Here is a question about implicit conversion from T (&) to ptrcarray<T>. I wrote a class template <class T> struct ptrcarray { T * array; size_t size;
31
by: Bjørn Augestad | last post by:
Below is a program which converts a double to an integer in two different ways, giving me two different values for the int. The basic expression is 1.0 / (1.0 * 365.0) which should be 365, but one...
2
by: Alex Sedow | last post by:
Why explicit conversion from SomeType* to IntPtr is not ambiguous (according to standart)? Example: // System.IntPtr class IntPtr { public static explicit System.IntPtr (int); public...
9
by: Girish | last post by:
Im trying to understand implicit type conversions from object -> string and vice versa. I have two classes, one Driver and one called StringWrapper. These are just test classes that try and...
1
by: tsar.omen | last post by:
Hello everyone, during my coding practice I have encounted the following problem: Vital code pieces: --- template <class T> class SmartPtr {
2
by: Harold Howe | last post by:
Howdy all, I am getting a compiler error regarding a consrained conversion. It complains that it can't make the type conversion, even though the generic type argument inherits from the target of...
6
by: Peter Lee | last post by:
what's the correct behaver about the following code ? ( C++ standard ) I got a very strange result.... class MyClass { public: MyClass(const char* p) { printf("ctor p=%s\n", p);
4
by: tom | last post by:
I have a code segment list below, for the function call "calc()" in the main function, a standard conversion from "double"->"int" is made while "double"->"LongDouble" is also viable, does anyone...
2
by: xtrigger303 | last post by:
Hi to all, I was reading Mr. Alexandrescu's mojo article and I've a hard time understanding the following. Let's suppose I have: //code struct A {}; struct B : A {};
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
1
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
1
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.