I’m working in an embedded microcontroller and I have to read/write multiple types data to Non-Volatile RAM (NVRAM). I’d like to avoid having to write separate read/write functions for each value to store in NVRAM like this:
void Write_Value1(int value);
int Read_Value1(void);
void Write_Value2(unsigned long value);
unsigned long Read_Value2(void);
...
That is definitely cumbersome to maintain as the list of items to read/write grows. There’s a couple of ways to tackle this in C++, templates for example. Using a template I could write a .Read() and .Write(T value) function that each item to read/write would have access to. Is there anyway to get this behavior from C? I suspect that there is some way, using some combination of void pointers and vtables. I’d like to handle this in a more polymorphic fashion and have the function for reading/writing each item to NVRAM called in a similar fashion.
You could do it with void pointer and sizes:
Then:
The
read_valuethen needs tomallocsomething and return it. This might just be overhead sometimes, when you’d rather read into an automatic. Then do:And finally, you could ‘simulate’ templates in all sorts of ways.