I'm looking to serialize a class that contains std::string to file and easily load this data in Python:
class A {
public:
int a;
char b;
bool c;
std::string s1;
std::string s2;
}
I have a very busy thread that deals with many instances of A. It takes interesting ones and adds them to a class for a less busy thread to write later.
class Blob {
public:
char data[1024]
size_t length;
}
void createBlob(void *data, int length) {
Blob saved_a;
saved_a.length = length;
memcpy(saved_a.data, a, length);
}
Then, the low priority thread asynchronously writes blobs to file: file.write(reinterpret_cast (&saved_a.length), sizeof(saved_a.length)); file.write(saved_a, saved_a.length);
These files are then read by Python and use struct library to load the data/handle endianness.
I don't have a great way to store the std::string (partially because I don't understand what guarantees there are on the life of a std::string). Would the logging thread be able to cast the saved_a.data to a type A and then read the strings? Or does the memcpy only save pointers to strings that may no longer be valid.
Copying the A structure isn't really possible because createBlob can take many different data structures (only requires a void * and a size). I'm willing to sacrifice platform independence and count out/test through the packing to make sure that the Python parser works, but really need to minimize the load put on the function that creates blobs and need to ensure that it can create blobs of many different data types.
If the std::string would remain valid when the low priority logger gets to them, he could recast the data and a do a full copy. Otherwise, is there a lightweight solution to serialize the structure before passing to createBlob function (comparable in performance to doing the memcpy)?