gbadev.org forum archive

This is a read-only mirror of the content originally found on forum.gbadev.org (now offline), salvaged from Wayback machine copies. A new forum can be found here.

Beginners > SRAM, Structs and memcpy

#20938 - TheMikaus - Thu May 20, 2004 6:25 am

I've been messing with the SRAM and I can save using the ((char *)SRAM)[offset] and load using the same just fine, but I was trying to get memcpy to work. That way I can just have a savegame struct.

typedef struct tagSaveGame
{
char data;
int moredata;
blah blah blah...
} SaveGame;

....
SaveGame theSave;
memcpy((char *)SRAM, &theSave, sizeof(theSave));
and memcpy(&theSave,(char *)SRAM,sizeof(theSave));

but it doesn't work. at all. I was just wondering if there was a way to get it to work right. (Mainly asking what I'm doing wrong)

#20945 - f(DarkAngel) - Thu May 20, 2004 1:18 pm

You have 8-bit rw access to SRAM. Using str or strh will pass only lower byte.

I don't know what libc memcpy does exactly, but if memcpy isn't writing 8-bit at time, then it sure will fail.
_________________
death scream...

#20952 - TheMikaus - Thu May 20, 2004 3:15 pm

Yeah. I realized that before I went to bed. I think memcpy is 16bit. So I made my own memcpy function that works (so far).

void mmcpy(void * dest, void * src, int size)
{
while(size > 0)
((char *)dest)[size] = ((char *)src[size--];
}

seems to work. Just means it writes the data in backwards but it's not a big deal . Might be a small performance hit if the GBA is particular, but easily fixable. I haven't tried this with funny sized structs (those that use bit fields), but I plan on doing that later.

Thanks for the fast reply :)

#21006 - sasq - Fri May 21, 2004 3:33 pm

since that is for chars only, a nicer way to write it would be;

void mmcpy(char * dest, char * src, int size)
{
while(size--) *dest++ = *src++;
}

#21287 - TheMikaus - Wed May 26, 2004 7:04 pm

The problem with having the parameters passed in as chars is the idea that you would have to type cast the variables going in.

I'm 90% sure that if you use void * you wont have to type cast. you just have to reference.

so instead of mmcpy((char *)&bob,(char *)&bobnew);
it would just be mmcpy(&bob,&bobnew);

So like a one line change in what yours says (looks much nicer your way) :)

and I don't know if I'm reading wrong, but the only reason I use the variable type char is because it uses 8 bits which is how much you're allowed to copy to SRAM at one time. It's not necessarily characters. I don't think you meant just coping letters, but I wasn't sure.