Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ anonymous struct pointer assignment

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?

like image 357
Qix - MONICA WAS MISTREATED Avatar asked Nov 28 '22 09:11

Qix - MONICA WAS MISTREATED


2 Answers

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.

like image 188
Jerry Coffin Avatar answered Dec 10 '22 12:12

Jerry Coffin


I think you have to use C++11's decltype:

oTwoShort = reinterpret_cast<decltype(oTwoShort)>(msg);
like image 30
CB Bailey Avatar answered Dec 10 '22 12:12

CB Bailey