0

I would like to take the memory generated from my struct and push it into a byte array (char array) as well as the other way around (push the byte array back into a struct). It would be even better if I could skip the string generation step and go directly to writing memory into the EEPROM. (Do not worry about the eeprom bit, I can handle that by reading & writing individual bytes)

// These are just example structs (I will be using B)
typedef struct {int a,b,c;} A;
typedef struct {A q,w,e;} B;

#define OFFSET 0 // For now

void write(B input)
{
  for (int i=0;i<sizeof(B);i++)
  {
    eepromWrite(i+OFFSET,memof(input,i));
  }
}

B read()
{
  B temp;
  for (int i=0;i<sizeof(B);i++)
  {
    setmemof(temp,i,eepromRead(i+OFFSET));
  }
  return temp;
}

This example I wrote is not supposed to compile, it was meant to explain my ideas in a platform independent environment.

PLEASE NOTE: memof and setmemof do not exist. This is what I am asking for though my question. An alternative answer would be to use a char array as an intermediate step.

8
  • It's hard to understand what you're asking for here, can you please clarify your question? Commented Apr 1, 2012 at 22:52
  • How do you want your structures packed? Commented Apr 1, 2012 at 22:58
  • Your question is unclear. Are you looking to make this work in a platform independent manner? If so you need a serialization & de-serialization mechanism. Commented Apr 1, 2012 at 23:00
  • @MahmoudAl-Qudsi I am trying to break out the memory allocated from a stuct into bytes (via one byte at a time). Then loop though those bytes to dump the struct into EEPROM. Commented Apr 1, 2012 at 23:01
  • So just replace setmemof with eepromWrite.... What am I missing here? Commented Apr 1, 2012 at 23:02

1 Answer 1

1

Assuming your structures contain objects and not pointers, you can do this with a simple cast:

save_b(B b) {
  unsigned char b_data[sizeof(B)];
  memcpy(b_data, (unsigned char *) &b, sizeof(B));
  save_bytes(b_data, sizeof(B));
}

Actually, you shouldn't need to copy from the structure into a char array. I was just hoping to make the idea clear.

Be sure to look into #pragma pack, with determines how the elements in the stuctures are aligned. Any alignment greater than one byte may increase the size unnecessarily.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.