Ive got some C++ 开发者_如何转开发code, that we use to serialize arbitrary data and store it into a specialized image format as metadata.
Anyways, it takes it as a void*. Can i just do a simple memcpy? Or is there a better way to do this?
STL string may not store the data in a continuos block of memory . Use c_str() method to get a c-style string out of it and serialize it . Since vector stores its data in a continuous manner you can directly serialize it.
For std::string you can use c_str() to obtain the char* pointing to the internal string.
For std::vector the standard dictates that the elements are contiguous in memory and so you can access the pointer to the beginning of the data as &v[0].
You should of course be careful with these since you are basically handing the library you are using a pointer to the internal data of the objects. If needed you can make a copy of the data using memcpy using the above as the src pointer but obviously you'll need to take care that you use the correct size. Without knowing the details of the function(s) you're passing this data to it's not possible for us to comment on whether such copying is needed or not.
As others have pointed out, &v[0] gives you a pointer to the array inside a vector.
However, be aware that serializing data using memcpy is generally not at all portable in C++. The data must be of Plain-Old-Data type (i.e. no non-trivial constructors, virtual functions, user defined destructor or such), but even then you should not expect to get the correct behaviour unless you read it back into to exact same program.
Changing target platform, compiler or even compiler settings can alter the format of the data. The compiler is for instance allowed to and usually will add padding fields in structs.
There are good libraries that allow you to serialize complex data, such as Boost Serialization, if you need to do that. It already has built-in support for std::vector and other standard types.
The STL Vector stores it's elements in contiguous memory, and therefore you can use memcopy to copy the elements knowing the element size and number.
精彩评论