简体   繁体   English

如何将C void *指针转换为指向结构的指针(将结构定义为字符串)?

[英]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. 我想打印由void*指针指向的内存中存储的信息。

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. 我认为这应该可行,因为调试器可以在被调试的进程中访问原始指针,并使用附加到可执行文件的调试信息(例如DWARF格式)来打印人类可读的信息。 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. 编辑:结构定义可能没有C,它可能是其他用户定义的格式,例如LLVM IR或drawf。

To show you how to interpret here you have small snippet. 为了向您展示如何解释,您有一个小片段。 It char array formated as : one char as type, next bytes data. 它的char数组格式为:一个char作为类型,下一个字节数据。 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 https://ideone.com/178ALz

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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