serialize a struct

M

markww

Hi,

I have a structure like this:


struct TEST {
int x, y, z;
string str;
vector<float> vFloat;
};


I need to serialize an instance of this struct into a stream of bytes
(its for insertion into a 3rd party file). This 3rd party library has a

function to insert the serialized buffer into their files that looks
like:


SetPrivateData(unsigned char *pData, int nSize);


It was suggested I do the following:


TEST t;


// how much space do we need?
int bufsize = sizeof(int)* 3 + sizeof(float)*t.vFloat.size() +
t.str.length()+1;


// create and clear the buffer
unsigned char *buf = new unsigned char[bufsize];
memset(buf, 0, bufsize);


unsigned char *pBuf = buf;


int *pIntBuf = (int *) buf;


// copy in the ints
*pIntBuf = t.x;
pIntBuf++;
*pIntBuf = t.y;
pIntBuf++;
*pIntBuf = t.z;
*pIntBuf++;


// copy in the floats
pBuf = (unsigned char *)pIntBuf;
vector<float>::pointer floatptr = &(t.vFloat[0]);


memcpy(pBuf, floatptr, t.vFloat.size()*sizeof(float);
pBuf += t.vFloat.size()*sizeof(float);


// copy in the string
strcpy(pBuf, t.str.c_str());


But I'm not sure if this is working correctly, the above executes but
dies when I try printing any portion of it to screen to examine the
contents using printf(). Is the above doing what I need it to do?


Thanks
 
D

David Harmon

On 3 Sep 2006 11:15:24 -0700 in comp.lang.c++, "markww"
But I'm not sure if this is working correctly, the above executes but
dies when I try printing any portion of it to screen to examine the
contents using printf(). Is the above doing what I need it to do?

I find the style of the mentioned code to be a step backward for
someone who is properly using string and vector, but let's not get
into that (unless you want to.) The actual problem I notice is that
you do not write out the vector size before the elements, and so
will have some difficulty figuring out how many elements to read
back later.

As for printf, I find it curious that the thing that is not working
for you is the ONE thing you did not post so that we could look at
it. Instead of printf, try e.g.

std::cerr << std::hex;
std::copy(buf, pbuf, std::eek:stream_iterator<int>(std::cerr, " "));

Note the <int> is significant.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,262
Messages
2,571,049
Members
48,769
Latest member
Clifft

Latest Threads

Top