Reputation: 1892
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
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:
void*
for genericness; at while casting to void*
you don't have to use typecastingreinterpret_cast<>
to show the reader that something 'dirty' is
happeningUpvotes: 0
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
Reputation: 934
unsigned char *p = (unsigned char*) &P;
Packet *pPacket = (Packet *)p;
Upvotes: 0