Why no offsetof for static struct?

FoxyBrown via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Mon Jul 10 13:01:39 PDT 2017


Cannot get the offset of static members of a struct

struct X
{
     __gshared public:
         int x;
}


X.x.offsetof < invalid.

We can clearly get a pointer to the static struct X since &X.x is 
effectively the address of X(regardless nomenclature and 
terminology issues in D trying to hide this).

e.g.,

auto p = cast(X*)&X.x;

will, for all practical purposes be a pointer to X.


auto GetStaticAddress(T)()
{
	mixin("auto p = cast(T*)&T."~__traits(allMembers, T)[0]~";");
	return p;
}

Of course, assuming that the first member is at the same location 
as the start of the struct and the elements are laid out in the 
same positions(not sure if this is guaranteed, but probably is).

Would be much nicer if we could just take the address of a static 
struct




More information about the Digitalmars-d-learn mailing list