Why no offsetof for static struct?

ag0aep6g via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Tue Jul 11 00:25:08 PDT 2017


On 07/10/2017 11:14 PM, FoxyBrown wrote:
> auto GetStaticAddress(T)()
> {
>      mixin("auto p = cast(T*)&T."~__traits(allMembers, T)[0]~";");
>      return p;
> }
> 
> 
> Returns the address of a struct's static members.

No, it returns the address of T's first member.

> It's pretty obvious, the compiler seems to instantiate the static 
> members simply as a sort of "singleton". They are laid out with the same 
> relative offsets as the struct(which is obvious, as that is the most 
> natural way). That is all that is needed to treat the memory the static 
> variables use as the struct in which they are part of. No need to make 
> it any more complex than that.

There may be cases where that happens, but it's not guaranteed. Here's 
an example where static members don't get stored together:

----
struct SA
{
     static int x;
     static immutable int y;
}

struct SB
{
     static int x;
     static immutable int y;
}

struct D
{
     int x;
     immutable int y;
}

const(void)*[] addressesOfMembers(alias thing)()
{
     import std.meta: AliasSeq;

     static if (is(thing)) alias T = thing;
     else alias T = typeof(thing);

     const(void)*[] addresses;
     foreach (m; AliasSeq!(__traits(allMembers, T)))
     {
         addresses ~= &__traits(getMember, thing, m);
     }
     return addresses;
}

void main()
{
     import std.stdio;
     writeln("members of SA: ", addressesOfMembers!SA);
     writeln("members of SB: ", addressesOfMembers!SB);

     D d;
     writeln("members of d:  ", addressesOfMembers!d);
}
----

Prints something like this (Ubuntu, x86-64):

----
members of SA: [7F7B2A294E90, 55EB7957FE94]
members of SB: [7F7B2A294E94, 55EB7957FE9C]
members of d:  [7FFDD1F2E4B8, 7FFDD1F2E4BC]
----

Note that SA's second member is stored far away from its first member. 
Same for SB. Also, SB's second member is stored between SA's members.

In contrast, d's members are packed together, because they're not static.


More information about the Digitalmars-d-learn mailing list