fork download
  1. #include <iostream>
  2. using namespace std;
  3.  
  4. #define asOFFSET(s,m) ((size_t)(&reinterpret_cast<s*>(100000)->m)-100000)
  5.  
  6. struct MyStruct {
  7. int var1;
  8. long var2;
  9. double var3;
  10. unsigned char L;
  11. int a;
  12. int b;
  13. int c;
  14.  
  15. };
  16.  
  17. int main() {
  18.  
  19.  
  20. cout << "offset of a = " << (int)asOFFSET(MyStruct,a);
  21.  
  22. }
  23.  
  24. // I have found this as the approach to calculate the position offset of any item `m` of any struct `s` // from the beginning of the structure.
  25. //The macro is (most likely) used by the scripting library to find out the internal layout of a class's
  26. // members without making assumptions about its type, architecture or inheritance model.
  27.  
  28.  
  29. // For most C++ programs, this information (memory layout) should ideally not be needed at all.
  30. // But in the off chance that you do need it (e.g. if you're writing an analyser / debugger), you would be
  31. // better off retaining this macro as-is
  32.  
  33. // The purpose of the macro is to determine, given *any* name of a struct and *any* name of a
  34. // member of that struct, the *distance in memory* from the beginning of an arbitrary instance of
  35. // the struct, and the location of that member in the same instance.
  36.  
  37. //`m` does not have a "type", and neither does `s`. The *entire concept of "type" goes out the
  38. // window* when you use macros. This stuff simply *is not C++*; it's basically a completely
  39. // separate language that's used to edit C++ code in-place. When the preprocessor runs,
  40. //`asOFFSET(MyStruct, a)` will be *literally replaced with the text* `((size_t)
  41. // (&reinterpret_cast<MyStruct*>(100000)->a)-100000)` before the compiler even begins its work.
  42.  
  43. // `((size_t)(&reinterpret_cast<MyStruct*>(100000)->a)-100000)` is intended to evaluate to 0,
  44. // because the `a` member of `MyStruct` instances appears at the beginning of each instance. I'm
  45. // not actually 100% sure that this is legal behaviour per the specification, but the intent is as
  46. // follows:
  47.  
  48. // * Pretend that there is an instance of `MyStruct` at the memory location `100000`, by treating the
  49. // number `100000` as if it were a pointer to a `MyStruct`.
  50.  
  51. // * Get the address in memory of the `a` member of this fake struct, and subtract `100000` again.
  52. // That gives us the distance from the beginning of the fake struct to the specified member of that
  53. // fake struct.
  54.  
  55. // * Cast that numeric value back to `size_t` (the numeric type used for measuring memory
  56. // allocations, an unsigned integer type).
  57.  
Success #stdin #stdout 0s 3340KB
stdin
Standard input is empty
stdout
offset of a = 20