I have C++ structure as
struct myStruct {
int a;
int b;
int c;
};
myStruct b;
int *ptr = &b.c;
How can I get myStruct object back from ptr?
(I know I can do this using pointer arithmatic like container_Of() in C. Basically something like
reinterpret_cast<myStruct*>(reinterpret_cast<char *>(ptr) - offsetof(myStruct, c));
I am asking if there is any recommended/elegant way?)
There's certainly no recommended way, as doing this is definitely not recommended at all in C++. This is one of those questions where the correct answer has to be "Don't do that!"
The whole reason for using C++ instead of C is that you want to encapsulate the structure of data inside classes with sensible operations defined on them, instead of allowing the whole program to have knowledge of the internal layout of data structures.
That said, the offsetof technique you describe will work on plain old data objects, because they are no different to C structs.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With