Creating a struct, typecast to char* and pull out elements of the struct

Started by
4 comments, last by smitty1276 15 years, 3 months ago
Basically what im trying to do (and please shoot me if this is really bad) is I have a struct with no alignment I am creating

# pragma pack (1)//turn off struct packing for this struct.
struct TEST
{
	WORD	Size;		//2 bytes
	WORD	ID;		//2 byte
	char	text[10];	//10 bytes
}UNALIGNED test2;
# pragma pack ()//turn it back to normal
now im taking this struct and sending it through winsock like so char *s=(char*)&test2 //copy our struct to a char* and I can receive it just fine and recast it to the struct, but what I was wondering is there anyway I can find out what Size and ID are without recasting to the struct... something like memcpy those bytes to a int, but I cannot find anything on the internet.. any help would be appreciated!
Advertisement
I'm not sure if this is the most proper way of doing this, but you should be able to get it by dereferencing your pointer

WORD* SizePtr = (WORD*)test2;
WORD* IDPtr = (WORD*)( test2 + sizeof(WORD) );

WORD Size = *SizePtr;
WORD ID = *IDPtr

[Edited by - Riraito on January 20, 2009 8:43:02 PM]
You sir are my hero =) thanks for the reply!
edit: worked like a charm
What's wrong with just casting it to the struct type?
Quote:Original post by smitty1276
What's wrong with just casting it to the struct type?

I assume he wants to determine which type to cast it to by looking at the size and ID fields. In which case the usual solution is to send a separate "Header" struct (or even just an enum) beforehand with that information. The receiver casts to the Header type, then determines what type the next received object will be based on the ID. You must ensure that you always send a Header before a Message.
Quote:Original post by scjohnno
Quote:Original post by smitty1276
What's wrong with just casting it to the struct type?

I assume he wants to determine which type to cast it to by looking at the size and ID fields. In which case the usual solution is to send a separate "Header" struct (or even just an enum) beforehand with that information. The receiver casts to the Header type, then determines what type the next received object will be based on the ID. You must ensure that you always send a Header before a Message.
Yeah, or you just inherit all of your datatypes from a PacketBase type that has that info in it.

struct PacketBase{    int packetType;    int packetSize;};struct AwesomePacket : public PacketBase{    int awesomeData;};

This topic is closed to new replies.

Advertisement