0

I am writing a generic function to generate JSON string from a structure which takes a structure as input and returns a JSON formatted string.

Example:

#define LF "\n"

 struct object {
    int number;
    char *name;
    char status;
};

char *json_stringify(void *s, char *type)
{
    char *result;

    ....
    ....
    return result;
}

int main()
{
    struct object obj ={
        .number = 1000,
        .name = "ajith",
        .status = 'S'
    };
    printf("Result : %s"LF, json_stringify(&obj,"struct object"));
    return 0;
}

I need to write the json_stringify() function which produce an output like follows,

{"number":1000,"name":"ajith","status":"S"}

But is it possible to identify the member variable names of a structure at runtime?

Where is the structure definition details are kept by the compiler?

Note: I am using a CentOS-6 Linux distribution with gcc.

Please help me... Thanks in advance.

Julio Guerra
  • 5,523
  • 9
  • 51
  • 75
  • 3
    No, unless you keep a separate description of the struct your program can refer to. Type names, struct member names, often variable names, are not generally retained in the compiled code. – Dmitri Jan 24 '17 at 06:41
  • thanks for your replay, but then how debugging toos such as gdb accessing the structure members? I heard about a program database (PDB) symbol file, that will contain the structure definition details. is there any possibility in that way? – Ajith C Narayanan Jan 24 '17 at 06:55
  • 1
    Debuggers use symbol tables from the executable files. (The files must be compiled with the `-g` option.) The symbol tables are not loaded into the RAM when a process is created. If you want, you can try reading a symbol table from the exec file yourself, but keeping the field names in an array is surely a much simpler solution. – DYZ Jan 24 '17 at 07:26
  • thanks for your suggestion DYZ. But i am planning to write a generic JSON parser. As you said, I can write a parser to read the structure definitions from source files and create an array of member names. But the problem is, when structure definitions are contained in different files, for example, if i want to stringify "struct stat" type, i may need to hard code the location of stat structure to /usr/include/sys/stat.h to read definition of "struct stat" and generate a member array. This is not i actually want. – Ajith C Narayanan Jan 24 '17 at 08:24
  • Is there any APIs like dlopen(), dlsym(), etc are available for accessing the symbol table? if not how can i read symbol table manually? – Ajith C Narayanan Jan 24 '17 at 08:25
  • @AjithCNarayanan you can start here: http://stackoverflow.com/questions/1101272/library-to-read-elf-file-dwarf-debug-information – John Zwinck Jan 24 '17 at 09:04

0 Answers0