-1

I want to replace object field access with functions to make it easy for a program analyzer I am building. Is there a simple way to do this? I came up with the following hack with my own set and get functions:

struct Foo
{
  int f1;
  int f2;
};

// convert v = t->f1 to v = (int)get(t, "f1")
void * get (struct Foo * t, char * name)
{
    if (!strcmp(name, "f1")) return t->f1;
    else if (!strcmp(name, "f2")) return t->f2;
    else assert(0);
}

// convert t->f1 = v; to set(t, "f1", v)
void set (struct Foo * t, char * name, void * v)
{
    if (!strcmp(name, "f1")) t->f1 = (int)v;
    else if (!strcmp(name, "f2")) t->f2 = (int)v;
    else assert(0);
}

Edit: C or C++ hacks would work.

JRR
  • 6,014
  • 6
  • 39
  • 59
  • 3
    C++ and C are different languages technically. So please choose which language you want. – kiner_shah Dec 27 '21 at 07:28
  • 2
    In which language are you trying to do that? Note that some otherwise helpful users get distracted if you tag more than one language and do not clearly explain why. – Yunnosch Dec 27 '21 at 07:28
  • Also, rather than having single function to handle get and set, better to have separate functions for each member, like get_f1() and set_f1(). – kiner_shah Dec 27 '21 at 07:29
  • 4
    You are a) trying to find ways to make programs be written so that your analyzer has an easier job b) trying to introduce parser-based language concepts into a compiled language c) ignoring the difference of C and C++. I think all three are unhelpful design decisions. I recommend to redesign, maybe after studying the concept of https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem – Yunnosch Dec 27 '21 at 07:34
  • 1
    A program analyzer does not need member name lookups in its own structures. It might need member name lookups in structures of programs it is analyzing. It would implement that using maps of the member names, which it constructs when parsing the structure declarations, and it could implement the maps using hash tables, various types of trees, or other methods. – Eric Postpischil Dec 27 '21 at 09:43
  • clang tooling might help for your analyser. instead of rewriting analysed code. – Jarod42 Dec 27 '21 at 10:37

1 Answers1

0

So, as far as I understand you are looking for some reflection library for c/c++? In this case, there is quite a big difference between c and c++.

For C++, you can use boost describe.

For C there are several libraries, bottom line all solution come down to defining your structs with macros, something like:

MY_STRUCT(s,
MY_MEMBER(int, y),
MY_MEMBER(float, z))

You can see a few examples here.

Yuri Nudelman
  • 2,874
  • 2
  • 17
  • 24