I want to use pointer magikry to save a C++ class using the following method that writes byte data into a file:
result Osp::Io::File::Write (const void *buffer, int length);
Parameters:
buffer
— A pointer to the user-supplied buffer that contains byte data to be writtenlength
— The buffer length in bytesExceptions:
E_SUCCESS
— The method is successful.E_INVALID_STATE
— The file has not been opened as yet.E_ILLEGAL_ACCESS
— The file is not opened for write operation, or access is denied due to insufficient permission.E_INVALID_ARG
— Either of the following conditions has occurred:
E_STORAGE_FULL
— The disk space is full.E_IO
— An unexpected device failure has occurred as the media ejected suddenly or file corruption is detected. I'd rather not assume that there will be any sort of buffering, although I am confident each byte won't occasion a whole block of flash to be rewritten but I was wondering if there is a niftier way to write all the data fields of a class (and nothing else, eg static fields) by, eg, a pointer to the object (*this
)?
In C++ you don't write "raw" objects into files, but rather serialize them. There's no magic, you need to write your serialization code yourself (overloading operators <<
and >>
, for convenience).
You can do it the old C-style by just dumping memory, but in addition to the problems this would generally cause with C (alignment, endian issues when transferring data between systems), you also get the problems introduced by C++ (internal class representation, possible "hidden" data members such as a v-table, etc).
If you want to ensure you read and write reliable data that can be transferred between different systems and/or different pieces of software - you better implement the serialization, and don't look for shortcuts.
You can use libraries like Boost.Serialization for that.