Pregunta

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?

¿Fue útil?

Solución

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.

Otros consejos

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

oTwoShort = reinterpret_cast<decltype(oTwoShort)>(msg);
reinterpret_cast<unsigned char*&>(oTwoShort) = reinterpret_cast<unsigned char*>(msg);

But, really?

As said you can't do a pointer cast but you can do this:

memcpy(&oTwoShort,&msg,sizeof(void*));
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top