5

I am reading Essential COM and encountered a macro 'BASE_OFFSET' from chapter 2 of the book and I don't really understand its syntax or why it's done that way.

#define BASE_OFFSET(ClassName, BaseName) \
(DWORD_PTR(static_cast<BaseName*>(reinterpret_cast<ClassName*>(0x10000000))) - 0x10000000)

Can anyone explain this macro and how we use this? In fact, the book uses this macro but since I don't really understand it, I don't see the practical usage of it. Thank you very much in advance.

Etienne de Martel
  • 34,692
  • 8
  • 91
  • 111
istudy0
  • 1,313
  • 5
  • 14
  • 22
  • 1
    By the way another standard windows macro [FIELD_OFFSET](http://msdn.microsoft.com/en-us/library/windows/hardware/ff545727(v=vs.85).aspx) get you offset of the named field of the structure. – Oleg Dec 10 '11 at 16:31
  • you are welcome! By the way it's defined so `#define FIELD_OFFSET(type, field) ((LONG)(LONG_PTR)&(((type *)0)->field))` – Oleg Dec 10 '11 at 16:49

1 Answers1

7

The macro makes up a dummy pointer to ClassName with the reinterpret_cast and then casts it to the BaseName with the static_cast.

In the presence of multiple inheritance, the address of a base class subobject is not always the same as the address of the object. This possibly-different-address is subtracted from the original dummy address, to obtain the offset of the BaseName subobject in a ClassName object. It's similar to offsetof, but for base class subobjects instead of members.

Diagram showing an example

This is only useful if you're doing some nasty low-level stuff.

R. Martinho Fernandes
  • 228,013
  • 71
  • 433
  • 510