mardi 30 novembre 2021

Any C++ macro that can export all member variables of a struct for pybind11 [duplicate]

I have some simple structure like:

struct Config {
  bool option1;
  bool option2;
  int arg1;
};

Using pybind11, I have to export the member variables like:

py::class_<Config>(m, "Config")
    .def_readwrite("option1", &Config::option1)
    .def_readwrite("option2", &Config::option2)
    .def_readwrite("arg1", &Config::arg1);

It is ok to write the above for some of these configs. But it becomes tedious when I have lots of this kind of simple structures to config many different targets.

Is there a convenience macro that I can write like:

PYBIND_EXPORT_STRUCT(Config1);
PYBIND_EXPORT_STRUCT(Config2);
...

and each scans and exports all the given struct's member variables?

Will it be helpful if I already write the structs in this form:

struct Config {
    ADD_PROPERTY(bool, option1);
    ADD_PROPERTY(bool, option2);
    ADD_PROPERTY(int, arg1);
}

ADD_PROPERTY() macro was originally used to generate property-like functions: get_var1(), set_var1().

Update

This question involves two parts:

  1. To reflect a variable back to its name string.
  2. To iterate through struct members.

I am aware of introspection to solve the first part, using typeid(arg1).name() to retrieve the name string.

For the second part, C++ does not directly support. However, I am trying to figure it out through some answers here.

The rest of the question is how to fuse the above two parts to get a working implementation for my imagined PYBIND_EXPORT_STRUCT() function.

Edit: that said, I don't mind reformimg my structs into totally different representations (like using some macro, or in tuples). Any will do as long as I don't have to enumerate my struct members again when exporting them with pybind11, and I can still use the variables like 'config1.option1=true' in C code.

Aucun commentaire:

Enregistrer un commentaire