-2

Before anything, I want to say the title is not the question.

My question is why can't you just send all the bytes of the structure and then cast it into that structure (giving you have the structure defined in both sides, which makes sense you have).

Thank you!

EDIT: Here's my current structure:

    struct COMPUTER_INFO
    {
        const char* Name;
        int Brightness;
        int Volume;
    }

I was thinking that it you can easily calculate the size of all that and then send it trough send().

SoLux
  • 162
  • 1
  • 9
  • 1
    It depends on: (a) what's in your structure; (b) how the receiving computer would understand the bytes sent if it had a different architecture (32-bit/64-bit, big vs little endian etc) . Please post an example structure so we have something concrete to answer. Also read how to post a [mcve] – Richard Critten Apr 22 '18 at 13:14
  • @RichardCritten I have edited it. #KillzoneKid alright, I will remove the first one – SoLux Apr 22 '18 at 13:20
  • Related: https://stackoverflow.com/questions/20066826/sending-a-structure-over-a-socket – Killzone Kid Apr 22 '18 at 13:25

2 Answers2

1

Name is a pointer (contains an address) that only makes sense to your program on your computer. If you sent this structure as bytes the receiving program would receive just the address not the characters that comprise the name. The received address would also not point to a valid location in memory in the receiving computer.

Brightness and Volume are ints - ints do not have a fixed size they are the "natural" word size of the computer (the standard does impose some restrictions). So the sizeof(int) on the sending and receiving computer may be different. There may also be encoding differences e.g. big vs little endian. See: https://en.wikipedia.org/wiki/Endianness

Richard Critten
  • 2,138
  • 3
  • 13
  • 16
  • I get it. I am using __int32 for the int. Also, I can get the address of the first element of Name and then just count the characters which I'll get with strlen. Wouldn't that work? – SoLux Apr 23 '18 at 19:11
0

in general you are right. You can, of course, send the raw byte streams. But how do you want the receiver to recognize the positions of the members of your structure in this byte stream? Especially, the char* in your example is of variable size, so this will not be possible. I recommend using the Boost serialization package. You can find a detailed tutorial here. The package will take care of "serializing" (packaging your object into a byte stream) and "deserializing" (constructing your object from the byte stream). It is absolutely convenient for nearly all STL containers and can easily be expanded for custom types.

mkuhlmann
  • 23
  • 5
  • Well, how about, let's say, filling up the PEB structure in your program? You get the address of the first element, and you cast it with the PEB structure. Everything falls into place because they are the same size. Right? – SoLux Apr 23 '18 at 19:16