0

I have a data struct that I am converting to uint8_t and sending it over a tcp socket connection. For the server side I have a python. How do I convert the data and display the struct information.

//data struct
typedef struct {
int enable;
string name;
int numbers[5];
float counter;
}Student;
 
//convert data to uint8 and send over tcp socket
uint32_t size = sizeof(student);
std:vector<std::uint8_t> data(size);
std::memcpy(data.data(), reinterpret_cast<void*>(&student),size)
sendDataOverTCPSocket(data);

Appreciate an example on how to do this.

Thank you

Used this https://www.digitalocean.com/community/tutorials/python-socket-programming-server-client socket_server.py code as the server application

1 Answer 1

1

You simply cannot do std::memcpy(data.data(), reinterpret_cast<void*>(&student),size)

&student is not a POD class. Specifically, in memory, the string name; member will be a small struct, say 16 bytes, with pointers to the actual content.

Use something like Protobuff or any other stock serialization. This is the only sane way.

Sign up to request clarification or add additional context in comments.

4 Comments

how would I read the bytes sent over the tcp socket in python code? appreciate an example
@jkafernando There is no point to reading the bytes sent because you sent the wrong data. All you will get is more confusion. You must fix the sender first. If you don't take Jeffery's advice and use an existing serializer, you'll have to write your own protocol. Sending raw structures rarely works as expected when both sides are written in the same language and when other languages get involved, you get a dog's breakfast. After the dog is done digesting it.
can you provide an example on how to use Protobuff or any other stock serialization.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.