Algorithmatic
Algorithmatic

Reputation: 1892

casting an object to char and then "uncasting it back"

If you have an object

struct Packet P;

that consists of

struct Packet {
    struct Packet_header header;
    unsigned char data[MAXIMUM_BUFFER_LENGTH];
};

and the header consists of

struct Packet_header {
    unsigned int checksum;
    unsigned int seq;
    unsigned int ack;
    unsigned int data_length;
};

If I try to cast the packet

(unsigned char*) &P

is there anyway I can "uncast" back to get my original packet P?

Upvotes: 0

Views: 1529

Answers (3)

iammilind
iammilind

Reputation: 69988

Yes, theoretically you can do that.
Since both Packet* and unsigned char* are pointer to data types, there is no information loss happening (if one of them is a function pointer then it's possible that information could be lost).

Few things to note:

  • Avoid such typecasting in first place
  • It's better to typecast to/from void* for genericness; at while casting to void* you don't have to use typecasting
  • Use reinterpret_cast<> to show the reader that something 'dirty' is happening

Upvotes: 0

Luchian Grigore
Luchian Grigore

Reputation: 258598

The easy way would be to use reinterpret_cast<Packet>(*(reinterpret_cast<Packet*>(pUC))), where pUC is the unsigned char*.

The correct ways is to have, in Packet_header, a conversion constructor and a cast operator (or cast-like method):

struct Packet_header {
    Packet_header(unsigned char*);  //construct object form unsigned char*
    operator unsigned char*();      //cast it back
    const unsigned char* getUC();   //or get an unsigned char*

    unsigned int checksum;
    unsigned int seq;
    unsigned int ack;
    unsigned int data_length;
};

Upvotes: 3

admiring_shannon
admiring_shannon

Reputation: 934

unsigned char *p = (unsigned char*) &P;
Packet *pPacket = (Packet *)p;

Upvotes: 0

Related Questions