Reputation: 15113
So no, this is not the best way to do things. However, for the sake of theory, how would one successfully assign a pointer value to a pointer of an anonymous struct?
#pragma pack(push,1)
struct
{
__int16 sHd1;
__int16 sHd2;
} *oTwoShort;
#pragma pack(pop)
oTwoShort = (unsigned char*)msg; // C-Error
produces:
error C2440: '=' : cannot convert from 'unsigned char *' to '<unnamed-type-oTwoShort> *'
The example assumes msg
is a valid pointer itself.
Is this possible? Since you don't have an actual type, can you even typecast?
Upvotes: 4
Views: 2463
Reputation: 1
As said you can't do a pointer cast but you can do this:
memcpy(&oTwoShort,&msg,sizeof(void*));
Upvotes: 0
Reputation: 490408
You can get the type with decltype
:
oTwoShort = reinterpret_cast<decltype(oTwoShort)>(msg);
This was added in C++11 though, so it won't work with older compilers. Boost has an implementation of roughly the same (BOOST_PROTO_DECLTYPE
) that's intended to work with older compilers. It has some limitations (e.g., if memory serves, you can only use it once per scope) but it's probably better than nothing anyway.
Upvotes: 11
Reputation: 792637
I think you have to use C++11's decltype
:
oTwoShort = reinterpret_cast<decltype(oTwoShort)>(msg);
Upvotes: 7
Reputation: 28188
reinterpret_cast<unsigned char*&>(oTwoShort) = reinterpret_cast<unsigned char*>(msg);
But, really?
Upvotes: 6