• Advertisement
Sign in to follow this  

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

This topic is 3284 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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!

Share this post


Link to post
Share on other sites
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]

Share this post


Link to post
Share on other sites
You sir are my hero =) thanks for the reply!
edit: worked like a charm

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites
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;
};

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement