在gdb
標籤中,前幾天只有question。我在下面列出了我的答案。正如俄羅斯就業指出的那樣,在C庫中實現反射似乎是可能的,因爲它是在gdb中完成的。
正如其他人所指出的那樣,反射並不是C或C++語言中的內容。有各種各樣的想法here
但是,反射是可能的在C/C + +第三方庫和調試符號在可執行文件或外部文件。
dwarfdump
可執行文件或多或少地做你所期望的。通過函數的DWARF信息細節,可以使用變量,類型等。以類似的方式,一個進程可以使用libdwarfdump功能來檢查自身。
下面是一個簡單的手動例如:
typedef struct somestruct
{
int i;
int j;
} somestruct ;
int abc(int x, float y , struct somestruct z){
char a;
int b ;
}
int main(int argc, char* argv[])
{
struct somestruct z;
abc(1,1.0f,z);
return 0;
}
和從dwarfdump
< 1><0x00000055> DW_TAG_subprogram
DW_AT_external yes(1)
DW_AT_name "abc"
DW_AT_decl_file 0x00000001 /tmp/dwarf.c
DW_AT_decl_line 0x00000009
DW_AT_prototyped yes(1)
DW_AT_type <0x0000004e>
DW_AT_low_pc 0x004004ed
DW_AT_high_pc <offset-from-lowpc>18
DW_AT_frame_base len 0x0001: 9c: DW_OP_call_frame_cfa
DW_AT_GNU_all_call_sites yes(1)
DW_AT_sibling <0x000000ad>
< 2><0x00000076> DW_TAG_formal_parameter
DW_AT_name "x"
DW_AT_decl_file 0x00000001 /tmp/dwarf.c
DW_AT_decl_line 0x00000009
DW_AT_type <0x0000004e>
DW_AT_location len 0x0002: 916c: DW_OP_fbreg -20
< 2><0x00000082> DW_TAG_formal_parameter
DW_AT_name "y"
DW_AT_decl_file 0x00000001 /tmp/dwarf.c
DW_AT_decl_line 0x00000009
DW_AT_type <0x000000ad>
DW_AT_location len 0x0002: 9168: DW_OP_fbreg -24
< 2><0x0000008e> DW_TAG_formal_parameter
DW_AT_name "z"
DW_AT_decl_file 0x00000001 /tmp/dwarf.c
DW_AT_decl_line 0x00000009
DW_AT_type <0x0000002d>
DW_AT_location len 0x0002: 9160: DW_OP_fbreg -32
通過仔細研究的部分輸出中,我們可以看到片段定義了函數 'ABC' 與arguements X, y和z。
參數x的類型是對鍵類型爲0x4e的類型表的間接引用。
查看輸出中的其他位置,我們可以看到類型爲0x4e的定義。類型0x2d是綁定回參數z的somestruct。
< 1><0x0000002d> DW_TAG_structure_type
DW_AT_name "somestruct"
DW_AT_byte_size 0x00000008
DW_AT_decl_file 0x00000001 /tmp/dwarf.c
DW_AT_decl_line 0x00000003
DW_AT_sibling <0x0000004e>
< 1><0x0000004e> DW_TAG_base_type
DW_AT_byte_size 0x00000004
DW_AT_encoding DW_ATE_signed
DW_AT_name "int"
ptrace的所述的組合,ELF,DWARF和/ proc文件系統允許GDB一個用於讀取過程的靜態和動態信息。另一個進程可以使用類似的功能來創建反射功能。
我已經使用此策略的變體來創建自定義調試器和內存泄漏檢測器。然而,我從來沒有見過這種用於商業邏輯的策略。
局部變量的名字是'z'。不知道你的問題是什麼。無論如何,沒有必要使用標準堆棧。而在x86/x64/ARM等最新平臺上,它很可能不會。而類型顯然是'int' C不支持動態類型(這包括編譯器擴展)。 – Olaf
使用標準C?不,沒有辦法。對於GCC,您可能需要[閱讀文檔](https://gcc.gnu.org/onlinedocs/)以查看它具有哪些(非標準)功能來幫助您。 –
[內省](https://en.wikipedia.org/wiki/Introspection_(computer_science))或[反思](https://en.wikipedia.org/wiki/Reflection_(computer_programming))是描述什麼你想...... – gilez