【问题标题】:How to cast a C void* pointer to a pointer to a struct (with definition of the struct as a string)?如何将 C void* 指针转换为指向结构的指针(将结构定义为字符串)?
【发布时间】:2019-01-29 17:47:47
【问题描述】:

我想打印存储在void* 指针指向的内存中的信息。

但类型信息在编译类型时不可用。

相反,类型定义的字符串将在运行时可用。有没有办法在运行时将指针转换为适当的类型,以便可以访问存储在指针指向的内存中的数据?

我认为这应该是可能的,因为调试器可以访问被调试进程中的原始指针,并使用附加到可执行文件的调试信息(比如 DWARF 格式)来打印人类可读的信息。我只是不知道这是如何在代码中完成的。

谁能告诉我这是谁做的?谢谢。

编辑。这是我想在代码中做的事情。

//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]; }");
}

编辑: struct 定义可能不是 C 语言,它可能是其他用户定义的格式,如 LLVM IR 或 drawf。

【问题讨论】:

  • 如果类型信息以字符串形式提供 - 那么不行,除了“手动”解析和重新解释数据之外别无他法。
  • 如果是dwarf格式,那么有可能吗?
  • C 不了解 dwarf 或任何格式。您可能会找到一些可以帮助您的库,但这与这里无关。
  • 就像@EugeneSh。写道。它解析矮树并解释数据。
  • 调试器是一款严肃的软件。它使用存储在编译后的二进制文件(符号)中的元数据——如果它是以特定方式编译的,并且按照我的第一条评论中指出的那样做一些不平凡的工作。

标签: c struct gdb llvm dwarf


【解决方案1】:

为了向你展示如何在这里解释你有一个小的 sn-p。它的字符数组格式为:一个字符作为类型,下一个字节数据。数组可以包含多于一对(类型、数据)

#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;
}

您可以对其进行测试并添加其他类型。 https://ideone.com/178ALz

【讨论】:

    猜你喜欢
    • 2023-03-26
    • 2011-09-15
    • 1970-01-01
    • 1970-01-01
    • 2016-11-10
    • 1970-01-01
    • 1970-01-01
    • 2015-01-24
    • 2016-03-21
    相关资源
    最近更新 更多