2

I have a data structure called Message and I need to turn it into a series of chars to send it via the network. The issue is the struct also contains a string field, and this field does not get cast correctly. I'm new to C++ and C programming, so I didn't realize this would be an issue. Here is the code

typedef struct {
  int id;
  string content;
} Message;

Message msg;
....
send_message(reinterpret_cast<char*>(msg));
6
  • 5
    there is (atleast, should) no c and c++, IMHO, it's c or c++. Choose yours. :-) Commented Mar 23, 2015 at 12:04
  • Why don't you just write a function that creates the string representation of your structure? Or a method of that structure that does it. Commented Mar 23, 2015 at 12:06
  • 7
    General rule of thumb: reinterpret_cast is the wrong tool. Commented Mar 23, 2015 at 12:07
  • 7
    You can't serialize complex class types like std::string or std::vector this way. Look out for a good serialization library like boost::serialization or google protobuf. Commented Mar 23, 2015 at 12:07
  • You can use regular socket api's to serialize ,send and receive . Commented Mar 23, 2015 at 12:07

1 Answer 1

4

At work, I did a class with template methods to serialize (into a char array) basic types and some std types, like vector and string.

class MySerializer{
public:
    // serialize operator
    template<typename T>
    friend MySerializer& operator<<( MySerializer&, const T&);

    // deserialize operator
    template<typename T>
    friend MySerializer& operator>>( MySerializer&, T& );
private:
    std::vector<unsigned char> v;
};

Then, if you need to serialize custom types, you can add specializations as needed. For basic types, you can just copy them byte to byte into v. Custom types need a few more work. Fore example, let's see how to serialize an std::string.

For this use case, you can look at std::string as a pair of asize_t where is stored the size of the string and a char* that points to string's chars. When you serialize a string, you could put its string::size(), casted for example to an uint32_t or uint64_t, into the serializer and then copy into the serializer string::size() characters starting from string::c_str(). When you will deserialize, first you need to read string's size from the serializer, and then put the proper number of chars into your output string.

You may be interested also in this question of mine.

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

1 Comment

How would you use this?

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.