-2

I'm trying to make portable library that can be used in esp32. Right now I have function that converts a struct to a char*. I populate the struct Message and then do:

memcpy(array,&message,sizeof(Message));

Later I would like to send this char* to a socket, receive it in the other side and reconstruct the struct. Is that possible ? Also, another question I have is:

struct Header{
    uint32_t source_id;
    uint32_t destinatary_id;
    uint32_t message_type;
};

struct Data {
    uint32_t dataSize;
    uint8_t* data;
};

struct Message{
    Header header;
    Data data;
    uint32_t timestamp;
};

char* array = new char[sizeof(Message)];
char array2[sizeof(Message)];

What is the difference between those two? array is a pointer and array2 is an array but I can't use array2 in this function because once I get out of the scope of the function the pointer to it is deleted.

  • 1
    This is two questions in one, and the second is a duplicate of https://stackoverflow.com/questions/79923/what-and-where-are-the-stack-and-heap. The first is generally a bad idea for multiple reasons, and the short answer is that the binary serialization is a complex topic that's best left to a specialized library. – Bartek Banachewicz Oct 09 '19 at 10:06
  • Thank you Bartek Banachewicz, I will look into that. Also I will look into a way to serialize and deserialize my structure :D – Filipe Amador Oct 09 '19 at 10:15

1 Answers1

0

I would like to send this char* to a socket, receive it in the other side and reconstruct the struct. Is that possible ?

Yes. It is possible. Standard C++ does not have a socket, or any other network communication API however, so you must consult the API offered be the target system to do that.

Also note that the message contains a pointer which will be of no use to a process on another system which has no access to the memory it is pointing. Furthermore, different systems represent data in different ways. As such, simply memcpying the message to the network stream will not work. How to do data serialisation is outside the scope of my answer.

What is the difference between those two?

One is an array with automatic or static storage, and the other is a pointer (with automatic or static storage) that points to first element of array in free store.

eerorika
  • 232,697
  • 12
  • 197
  • 326