std.reflection prototype

bitwise via Digitalmars-d digitalmars-d at puremagic.com
Thu Apr 16 16:25:25 PDT 2015


On Thu, 16 Apr 2015 02:22:25 -0400, Jacob Carlborg <doob at me.com> wrote:

> In D I would assume this would eventually be possible:
>
> class Foo { int a; }
> class Bar : Foo { int b; }
>
> Foo f = new Bar;
>
> auto offset = typeid(f).getMemeber("b").offset;
> auto ptr = cast(int*)(cast(void*)f + offset);
> *ptr = 4;

Ok, that sounds right. D has no multiple or virtual inheritance, so I  
guess things should be fine. C# is the same way(single inheritance,  
interfaces) which is likely designed to avoid these kinds of issues.

I would be modifying the offTi() property though, not getMembers().  
getMembers() actually works right now, although it's kinda useless.  
Basically, if you put any function named "getMembers" at module scope, the  
address of that function can be retrieved using ModuleInfo.xgetMembers().

///////////////
module mainMod;

template isField(alias T) {
     enum hasInit = is(typeof(typeof(T).init));
     enum isManifestConst = __traits(compiles, { enum e = T; });
     enum isField = hasInit && !isManifestConst;
}

MemberInfo[] getMembers()
{
     mixin("alias " ~ .stringof[7..$] ~ " mod;");

     MemberInfo[] members;

     foreach(memberName; __traits(allMembers, mod))
     {
         alias Identity!(__traits(getMember, mod, memberName)) member;

         static if(isField!member)
             members ~= new MemberInfo_field(memberName, typeid(member), 0);
     }

     return members;
}

int a = 1;
int b = 2;
int c = 3;

void main()
{
     foreach(mi; ModuleInfo)
     {
         if(mi.name == "mainModule")
         {
             alias MemberInfo[] function() getMembers_type;
             getMembers_type getMembers =  
cast(getMembers_type)mi.xgetMembers();

             foreach(m; getMembers())
                 writeln(m.name);
         }
     }
}

Output:
a
b
c

////////////////

offTi() however, even though it's documented, returns an empty array. I'm  
not sure what the motivation originally was for having an array of  
TypeInfo and offsets without the field names, but the dead code predates  
D2. I suppose you could do binary serialization...

Anyways, I've put the reflection library to rest for now. Hopefully I'll  
have some time in the next little while to try and get offTi() working.


More information about the Digitalmars-d mailing list