[英]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.