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,
Mark
 

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
473,769
Messages
2,569,582
Members
45,065
Latest member
OrderGreenAcreCBD

Latest Threads

Top