Flattening a C structure to a byte array

31 Aug 2010

Assuming a simple structure that does not contain pointers, to write the structure to a file I would flatten it to a byte array.

I have normally done this by making a void pointer to the structure, and the copying the void pointer contents to a char pointer. The mbed compiler will not let me do this. So how is it done?

31 Aug 2010

This should work:

struct MyStruct
{
    int data0;

    int data1;

    int data2;
};

int main() 
{

    MyStruct test;

    FILE* fp = fopen("myfile", "w");

    fwrite(&test, sizeof(MyStruct), 1, fp);

    fclose(fp);

    return 1;
}
I've not ran it, but it builds (or at least did before I pasted it here and changed the format a little :) )

 

31 Aug 2010

Hi John,

Matthew has already given you a solution, but just to complete the details...

It is complaining because you are not allowed implicit cast from (void*). So, for example:

struct mystruct {
    int a;
    char b;
    short c;
};

int main() {
    mystruct x;
    char *p1 = (char*)&x;           // ok
    char *p2 = (char*)(void*)&x;    // ok
    // char *p3 = (void*)&x;        // not ok, implicit cast from (void*) to (char*)
}
I'd assume the first is what you'd naturally do.

Simon

31 Aug 2010 . Edited: 31 Aug 2010

this is more like you described, and builds too, do you have an example of the code that doesn't work?

MyStruct test2;

void* vptr_test = &test2;

uint8_t buffer[sizeof(MyStruct)];

memcpy(buffer, vptr_test, sizeof(MyStruct));
31 Aug 2010

I think I'm out of the woods _ Thanks