简体   繁体   中英

How to cast a C void* pointer to a pointer to a struct (with definition of the struct as a string)?

I'd like to print the information stored a memory pointed by a void* pointer.

But the type information is not available at the compile type.

Instead, the string of the definition of the type will be available at the run time. Is there a way to cast the pointer to the appropriate type at the run time so that the data stored in the memory pointed by the pointer can be accessed?

I think that this should be possible as debugger can access raw pointers in the process being debugged and use the debugging information (say in DWARF format) attached to the executable to print human-readable information. I just don't know how this is done in code.

Could anybody let me know who this is done? Thanks.

EDIT. Here is what I want to do in code.

//definition
void myprint(void *p, const char *struct_def) {
//print the content in p according to struct_def, struct_def can be any valid struct definition in C.
}

//call
myprint(p, "struct s { int n; double d[10]; }");
}

EDIT: The struct definition may not have be in C, it could be in other user defined format, like LLVM IR or drawf.

To show you how to interpret here you have small snippet. It char array formated as : one char as type, next bytes data. The array can contain more than one pair (type, data)

#include <stdio.h>
#include <string.h>

char *print_x(char *str)
{
    union
    {
        int i;
        unsigned u;
        long l;
        long long ll;
        float f;
        double d;
    }data;

    switch(*str)
    {
        case 'd':
            memcpy(&data, str + 1, sizeof(double));
            printf("%f", data.d);
            return str + 1 + sizeof(double);
        case 'i':
            memcpy(&data, str + 1, sizeof(int));
            printf("%d", data.i);
            return str + 1 + sizeof(int);
        /* another formats */
        default:
            printf("Not implemented");
            return NULL;
    }
}
int main()
{
    char data[100];
    double x = 1.234;
    int z = 4567;

    char *str = data;

    data[0] = 'd';
    memcpy(&data[1], &x, sizeof(double));
    data[1 + sizeof(double)] = 'i';
    memcpy(&data[2 + sizeof(double)], &z, sizeof(int));

    while((str = print_x(str)))
    {
        printf("\n");
    }

    return 0;
}

You can test it and add other types. https://ideone.com/178ALz

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM