我想把用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]; }");
}
编辑:结构定义可能不是C语言,它可能是其他用户定义的格式,如LLVM IR或drawf。
发布于 2019-01-30 02:15:56
为了向你展示如何在这里解释,你有一小段代码。它字符数组格式为:一个字符作为类型,下一个字节数据。数组可以包含多个对(类型、数据)
#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
https://stackoverflow.com/questions/54426848
复制相似问题