serialize a struct



 DEVELOP > c-Plus-Plus > serialize a struct

LINK TO THIS PAGE  


rating :  0   |  0


  Page 1 of 1

1

 
Topic: DEVELOP > c-Plus-Plus
User: "markww"
Date: 03 Sep 2006 01:15:24 PM
Object: serialize a struct
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
.

User: "David Harmon"

Title: Re: serialize a struct 03 Sep 2006 05:02:15 PM
On 3 Sep 2006 11:15:24 -0700 in comp.lang.c++, "markww"
<markww@gmail.com> wrote,

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::ostream_iterator<int>(std::cerr, " "));
Note the <int> is significant.
.


  Page 1 of 1

1

 


Related Articles
 

NEWER

pg.1232     pg.940     pg.716     pg.544     pg.412     pg.311     pg.234     pg.175     pg.130     pg.96     pg.70     pg.50     pg.35     pg.24     pg.16     pg.10     pg.6     pg.3     pg.1

OLDER