c++ – I want to specify the member of struct as a character string and refer to it.

Question: Question:

I am considering how to write general-purpose processing in C ++ for the code implemented in C language (unchangeable).

For example, if the C side has the following structure definition,

typedef struct
    int     nvalue;
    float   fvalue;
} Test_t;

Is there a way to implement the following Create_strucure / Get_member in C ++?

auto sparam = Create_structure("Test_t");
auto* pvalue_1 = Get_member(&sparam, "nvalue");
*pvalue_1 = 1;
auto* pvalue_2 = Get_member(&sparam, "fvalue");
*pvalue_2 = 2.3;

//Create_strucure : 文字列で指定されたstruct型を返却

The purpose is to write a universally usable process for a huge number of sturucts.
I think it would be easier if the struct / member reference could be done as a string, but is that possible?

Thank you.

Answer: Answer:

If the immutable implemented code is provided as a compiled library and Test_t is also provided as an opaque type, it is not possible because the information is lost.

If you have a header file but you can't change it, the principle is to analyze the header with clang -Xclang -ast-dump=json in advance, dump the AST to a file, and read it from JSON at runtime. I think it is possible.

There was a tool & library that actually did the same thing with Clang libtooling.

The comment "I want to get GetComponent in C ++!" Seems to be a similar story in Visual Studio.

Scroll to Top