Click to See Complete Forum and Search --> : Casting angst (makes me feel like a newbie)


solosnake
October 4th, 2002, 06:43 AM
Hello guys,

Can anyone tell me a safe, nice way to cast between an integral type and a pointer to an object? And vice-versa? I want to use std C++.

eg class CMyThing { ..... };

int main()
{
CMyThing *pObj;

float f;

pObj = some_cast<????>( f );
}

Please dont comment on the why's of this type of operation. I HAVE to do it to work with my current projects legacy code. Its not my fault,honest :) But I would like to rewrite the old casts that were there to use the correct relevant casts. I had understood reinterpret_cast<> to allow casting arbitrarily, but three compilers I have tried refused to cast a float to a class pointer.

Thanks for all help.

- solosnake

jwbarton
October 4th, 2002, 07:45 AM
Casting between pointers and integer types does work with reinterpret_cast. Your problem is that a float is not an integer type.

So the following does work:


int value = 5;
CMyThing *pObj = reinterpret_cast<CMyThing *>( value );


In order to stuff a float value into a pointer, one way is to cast the lvalue so that you can assign a float on top of the pointer.

(Don't ever use this pointer as a pointer).


float f = 10.0;
* reinterpret_cast<float *>( &pObj ) = f;


What this code is doing is treating the address of pObj as a pointer to a float, and the dereferencing it so that the float can be assigned.

Best regards,
John

Graham
October 4th, 2002, 07:52 AM
Float is not an integral type. I would have thought that (unsigned) int or long would be better suited, depending on which one (if either) is the same size as your pointer.

Alternatively, find the author of the troublesome code and point out the error of their ways to them.

solosnake
October 4th, 2002, 08:06 AM
Thanks for the casting help.

Also I used integral to mean 'native', which to me includes 'floats' etc, however you are correct, in C++ parlance this does mean only the integer types.

Thanks for the help!

- solosnake