The "right" way to do this is by using the offsetof()
macro from <stddef.h>
. Unfortunately offsetof()
has some fairly draconian restrictions in C++:
Because of the extended functionality of structs in C++, in this language, the use of offsetof
is restricted to "POD [plain old data] types", which for classes, more or less corresponds to the C concept of struct (although non-derived classes with only public non-virtual member functions and with no constructor and/or destructor would also qualify as POD).
So if you make a
and b
public and get rid of TestMem
's constructor, you can write something like this to access a
:
C++ style:
#include <cstddef>
int vala = *reinterpret_cast<int *>(reinterpret_cast<char *>(&o1)
+ offsetof(TestMem, a));
C style:
#include <stddef.h>
int vala = *(int *) ((char *) &o1 + offsetof(TestMem, a));
Notice that you need to use &o1
here, not p
, which is a function pointer. The address of TestMem::TestMem1
won't have any relation to the locations of a
and b
. Class methods don't reside in memory anywhere near class member variables.
The "wrong" way is to just guess at where a
and b
are in memory. Most likely they are at offsets 0 and 4 from the start of o1
, respectively. So this code would work most of the time:
int vala = *(int *) ((char *) &o1 + 0);
int valb = *(int *) ((char *) &o1 + 4);
There are a lot of assumptions here. This assumes that ints are 4 bytes and that there's no padding between a
and b
. On the other hand it doesn't have any of the restrictions from above: a
and b
don't need to be public, you can have a constructor, whatever.