views:

61

answers:

2

Now I have a database, which one field type is an array of byte.

Now I have a piece of memory, or an object. How to convert this piece of memory or even an object to a byte array and so that I can store the byte array to the database.

Suppose the object is

Foo foo

The memory is

buf         (actually, don't know how to declare it yet)

The database field is

byte data[256]

Only hex value like x'1' can be insert into the field.

Thanks so much!

+2  A: 

There are two methods.

One is simple but has serious limitations. You can write the memory image of the Foo object. The drawback is that if you ever change the compiler or the structure of Foo then all your data may no longer loadable (because the image no longer matches the object). To do this simply use

&Foo

as the byte array.

The other method is called 'serialization'. It can be used if the object changes but adds a lot of space to encode the information. If you only have 256 bytes then you need to be watchful serialization doesn't create a string too large to save.

Jay
It might help if you show the casting...
Steven Sudit
+1  A: 

Boost has a serialization library you may want to look at, though you'll need to careful about the size of the objects created. If you're only doing this with a small set of classes, you may want to write the marshalling and unmarshalling functions yourself.

From the documentation:

"Here, we use the term "serialization" to mean the reversible deconstruction of an arbitrary set of C++ data structures to a sequence of bytes. "

pythonic metaphor