Mariska
Mariska

Reputation: 1953

Simple serialization example in c++

I have the following struct:

typedef struct{
    int test;
    std::string name;
} test_struct;

Then, I have the following code in the main function:

int main(int argc, char *argv[]){
    test_struct tstruct;
    tstruct.test = 1;
    tstruct.name = "asdfasdf";

    char *testout;
    int len;

    testout = new char[sizeof(test_struct)];

    memcpy(testout, &tstruct, sizeof(test_struct) );
    std::cout<< testout;
}

However, nothing gets printed. What's wrong?

Upvotes: 1

Views: 367

Answers (2)

alecbz
alecbz

Reputation: 6488

Try NULL-terminating the string and also emitting a newline:

testout = new char[sizeof(test_struct) + 1];

memcpy(testout, &tstruct, sizeof(test_struct));
testout[sizeof(test_struct)] = '\0';
std::cout<< testout << std::endl;

However, as user3543576 points out, the serialization you get from this process won't be too useful, as it will contain a memory address of a character buffer, and not the actual string itself.

Upvotes: 0

user3543576
user3543576

Reputation: 54

sizeof(std::string) yeilds same value always. It will not give you the runtime length of the string. To serialize using memcpy, either change the struct to contain char arrray such as char buffer[20] or compute the size of the required serialized buffer by defining a method on the struct which gives the runtime length of the bytes. If you want to use members like std::string, you need to go through each member of the struct and serialize.

memcpy(testout, (void *)&tstruct.test,  sizeof(int) );
memcpy(testout+sizeof(int), tstruct.name.c_str(),tstruct.name.length() );

memcpy against the entire struct will not work in such scenarios.

Upvotes: 1

Related Questions