Created
April 5, 2018 19:29
-
-
Save AndrewGaspar/50a192070d4df9feb56f29ae9428423d to your computer and use it in GitHub Desktop.
offset to base
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <cstddef> | |
#include <cstdio> | |
struct A | |
{ | |
int a; | |
}; | |
struct B | |
{ | |
int b; | |
}; | |
struct C : A, B | |
{ | |
int c; | |
}; | |
const C *my_c = reinterpret_cast<C *>(alignof(C)); | |
const ptrdiff_t offset_from_c_to_a = | |
reinterpret_cast<ptrdiff_t>( | |
reinterpret_cast<char const *>(static_cast<A const *>(my_c)) | |
- reinterpret_cast<char const *>(my_c)); | |
const ptrdiff_t offset_from_c_to_b = | |
reinterpret_cast<ptrdiff_t>( | |
reinterpret_cast<char const *>(static_cast<B const *>(my_c)) - | |
reinterpret_cast<char const *>(my_c)); | |
B *b_from_opaque_c_pointer(void *c_pointer) | |
{ | |
return reinterpret_cast<B *>((char *)c_pointer + offset_from_c_to_b); | |
} | |
int main() | |
{ | |
C data; | |
data.a = 1; | |
data.b = 2; | |
data.c = 3; | |
auto &data_as_b = *b_from_opaque_c_pointer(&data); | |
printf("data_as_b.b = %d\n", data_as_b.b); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment