How would I implement something similar to the Objective-C @encode() compiler directive in ANSI C?

后端 未结 3 839
后悔当初
后悔当初 2021-02-03 13:06

The @encode directive returns a const char * which is a coded type descriptor of the various elements of the datatype that was passed in. Example follows:

struct         


        
3条回答
  •  清酒与你
    2021-02-03 13:11

    One way to do it would be to write a preprocessor, which reads the source code for the type definitions and also replaces @encode... with the corresponding string literal.

    Another approach, if your program is compiled with -g, would be to write a function that reads the type definition from the program's debug information at run-time, or use gdb or another program to read it for you and then reformat it as desired. The gdb ptype command can be used to print the definition of a particular type (or if that is insufficient there is also maint print type, which is sure to print far more information than you could possibly want).

    If you are using a compiler that supports plugins (e.g. GCC 4.5), it may also be possible to write a compiler plugin for this. Your plugin could then take advantage of the type information that the compiler has already parsed. Obviously this approach would be very compiler-specific.

提交回复
热议问题