How do I dump an arbitrary struct in C?

后端 未结 4 1075
日久生厌
日久生厌 2021-01-12 03:07

I don\'t know which direction to go,perhaps something like reflection will help?

4条回答
  •  广开言路
    2021-01-12 03:52

    The answer of @Kerrek SB works realy well, I just post how to use it in a function using a void pointer.

    int dump(void *myStruct, long size)
    {
        unsigned int i;
        const unsigned char * const px = (unsigned char*)myStruct;
        for (i = 0; i < size; ++i) {
            if( i % (sizeof(int) * 8) == 0){
                printf("\n%08X ", i);
            }
            else if( i % 4 == 0){
                printf(" ");
            }
            printf("%02X", px[i]);
        }
    
        printf("\n\n");
        return 0;
    }
    
    int main(int argc, char const *argv[])
    {
        OneStruct data1, data2;
    
        dump(&data1, sizeof(OneStruct));
    
        dump(&data2, sizeof(OneStruct));
    
        return 0;
    }
    

提交回复
热议问题