Topic: Portability of Casting
Author: steve@taumet.com (Steve Clamage)
Date: Thu, 14 Jan 1993 17:10:26 GMT Raw View
JIMI@RALVM5.VNET.IBM.COM (Jim Meyers) writes:
>A certain "C" API has defined a series of structures:
>struct Base1 { ... }; // Never contains methods - only data members
>struct Base2 { ... }; // Never contains methods - only data members
>etc.
>There is a function in that API, foo, which takes a pointer to any of these
>Base structs as a parameter by casting to a void*. e.g.
>Base1 b1;
>Base2 b2;
>int rc = foo( (void*)&b1 );
>rc = foo( (void*)&b2 );
You are never guaranteed good results when you cast a pointer of one
type to a pointer to a different type. (You can always cast to void*
and back to the original type, but you can't do much with a void*
except pass it along or cast it back.)
When you cast a pointer-to-class to void*, you lose important
information. Further casts from the void*, other than immediately
back to the original type, are not guaranteed to work, and in general
will not work.
Whether the specific case you mention will work depends on details
of implementations which are not promised by the language definition.
--
Steve Clamage, TauMetric Corp, steve@taumet.com
Author: JIMI@RALVM5.VNET.IBM.COM (Jim Meyers)
Date: Wed, 13 Jan 93 13:45:58 EST Raw View
A friend of mine (honest) came to me today with the following scenario:
A certain "C" API has defined a series of structures:
struct Base1 {
...
}; // Never contains methods - only data members
struct Base2 {
...
}; // Never contains methods - only data members
etc.
There is a function in that API, foo, which takes a pointer to any of these
Base structs as a parameter by casting to a void*. e.g.
Base1 b1;
Base2 b2;
int rc = foo( (void*)&b1 );
rc = foo( (void*)&b2 );
The question, then, is it always safe to do the following cast when BaseN
only contains data members (i.e. no methods or virtual methods)?
class Derived : public Base1 {
...
virtual int bar(); // Derived class may or may not have virtual methods
...
};
Derived d;
int rc = foo( (void*)(Base1*)&d );
I understand that this will not work if Base1 is a virtual base class. I
am not sure, however, if this cast will always produce a Base1 object which
does not have a vtbl. Are vendors free to associate a vtbl with the Base1
part of d?
Also, the discussion of this topic in the ARM (5.4) mentions "sub-objects".
Can someone help me with a definitive explanation of a sub-object in this
context? Thanks.
--Jim
-------------------------------------------------------------------------
Jim Meyers | Voice: 919-543-5999
IBM Networking Systems | Fax: 919-543-1286
LAN Systems Workstation Technology |
Research Triangle Park, NC 27709 | Internet: jimi@ralvm5.vnet.ibm.com
-------------------------------------------------------------------------
=======================================================================