[英]How to cast a C void* pointer to a pointer to a struct (with definition of the struct as a string)?
我想打印由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。
为了向您展示如何解释,您有一个小片段。 它的char数组格式为:一个char作为类型,下一个字节数据。 该数组可以包含多个对(类型,数据)
#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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.