0

The offsetof(type, member) returns the offset value in bytes from the beginning of the layout of type to its member.

I am pretty sure the language does not provide a way to do the reciprocal: a memberof(type, offset) to go from a type and offset to a pointer to member. Is there a way to achieve that? Without abusing the language? In a cross-platform way? In a constexpr way?

struct my_type_t type {
  var_type_t m_var;
};

I can do:

size_t offset_in_bytes = offsetof(my_type_t, m_var);

I am looking for:

var_type_t my_type_t::* ptr_to_var_member = memberof(my_type_t, offset_in_bytes);
gg99
  • 445
  • 6
  • 12
  • 1
    Why do you need a pointer-to-member? If you have an offset, start, and known type, you can obtain a regular pointer to the member. – StoryTeller - Unslander Monica Mar 27 '23 at 10:46
  • Maybe using [this method](https://stackoverflow.com/questions/27687455/statically-iterate-over-all-members-of-a-c-struct) and try to match the offset to identify the member. – nielsen Mar 27 '23 at 11:02
  • @StoryTeller-UnslanderMonica: if I have a type, it does not mean I have a pointer to an instance that would allow me to obtain a regular pointer - I might want to just keep the pointer to member around until I have a pointer to the known type instance. – gg99 Mar 27 '23 at 11:32
  • 1
    Why not just keep the offset around then? – StoryTeller - Unslander Monica Mar 27 '23 at 11:33

0 Answers0