I working on a project in a microcontroller and I need to persist some settings. Pretend this is an iPod. I need to save various settings like CurrentSongPlaying
, CurrentVolume
, etc. so that when I turn on again I can restore those settings. The trouble I'm running into is that makes sense to store all my Non-Volatile Settings in a single struct that I can serialize/de-serialize from memory but I can't find a way to make that happen without the class doing the serialization/de-serialization from non-volatile memory including every class that contains a setting that will need to be saved for size/type information. Is there some sort of design pattern that will allow me to persist all these settings to memory without having to know about what I'm saving?

- 12,082
- 10
- 61
- 69
-
Can you show an example, pseudo-code at the very least, of what you are trying to achieve? – netcoder Aug 02 '12 at 19:01
-
Can you not move to C++? Inheritance/polymorphism makes all this kind of stuff much easier! – Martin James Aug 02 '12 at 20:29
-
1Looks like you just need an associative array. – netcoder Aug 03 '12 at 00:44
-
@netcoder - That looks to be exactly what I need, you should make your comment an answer. – Joel B Aug 03 '12 at 19:08
2 Answers
Looks like you just need an associative array. An associative array (or map) is a container that allows you to map different values to unique keys. It can have a fixed or dynamic size depending on the implementation. Coupled with a proper serialization mechanism, it allows you to save and restore its state without having to know its content in advance.
However, C does not provide this data structure out-of-the-box. Look at this question for a few implementations. The most common implementation is the hash table, also called a hash map.
OOP and classes are not easy to implement in C.
If using C is a must, I would write the struct to file.
Then I would read them and parse them during initialization upon reboot.
You can think of this as serializing your structs yourself.

- 1
-
That's the approach I suggested in my question, the problem is that I have to include all the other "classes" (header files) for any "object" (type) that I want to serialize so the struct can know about them. How do I avoid the "class" that does the writing/reading having to include every file that contains an "object" I would like to save in memory. – Joel B Aug 02 '12 at 22:20