简体   繁体   中英

pointers inside a struct with send

I have the following struct and I'm trying to send over the network to another application

 struct protocol
  {

     char protocol;
     char field1;
     char field2;
     char field3;
     char field4;
     char field5;
     char field6;
     char field7;
     char field8;
     char msg_id;
     char msg_length;
     char *msg;

  };

The problem I'm having is that I'm not sure how to send this struct over the network as there is a pointer pointing to a string in it, and memcpy the struct to buffer won't work, is the below the only way to do it?

memcpy (buffer, protocol->protocol, char)
memcpy (buffer, protocol->field1, char)
...
memcpy (buffer, protocol->msg, protocol->length)

then send the buffer

是的,如果要发送到(可能是)自己流程之外的内容,则这种编组或序列化是唯一可行的方法。

You will need to serialize the structure into a buffer of some sort. Your sequence of copies is correct in concept only; there are a myriad details to resolve:

char buffer[sizeof(struct protocol) + protocol->msg_length]; // Over-allocation

buffer[0] = protocol->protocol;
buffer[1] = protocol->field1;
...
buffer[8] = protocol->field8;
buffer[9] = protocol->msg_id;
buffer[10] = protocol->msg_len;
memcpy(&buffer[11], protocol->msg, protocol->msg_len);

Now you can write the correct length of buffer ( 11 + protocol->msg_len ) to send.

This is particularly simple; there are no endian-ness issues to worry about. Generally, with multi-byte values like short or int or long long , you have to worry about the transmitted byte order.

If you can restrict certain aspects of the data you're sending, such as "msg_len is never more than X bytes", you could do something like this:

#define MAX_MSG_LEN 1000
struct protocol
{
 char protocol;
 char field1;
 char field2;
 char field3;
 char field4;
 char field5;
 char field6;
 char field7;
 char field8;
 char msg_id;
 char msg_length;
 char msg[MAX_MESSAGE_LEN];
};

You'll need to calculate how much overhead there is before msg, and then use msg_length to determine the total size of the buffer you need to send.

Or, another method is:

struct protocol
{
 char protocol;
 char field1;
 char field2;
 char field3;
 char field4;
 char field5;
 char field6;
 char field7;
 char field8;
 char msg_id;
 char msg_length;
 char msg[1];
};

And then use struct procotol *msg_ptr = malloc(sizeof(struct protocol) + msg_len-1); when you need to form a message.

Both these methods will have the drawback that if you have "gaps" in the struct, you need to cope with that at the other end (which may have different rules for gaps, if it's compiled with a different compiler, for a different processor, or simply with different compiler switches)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM