Need runtime reflection?

lijie cpunion at gmail.com
Mon Jul 16 10:22:56 PDT 2012


I want to imitate golang's interface in D, to study D's template. I wrote
some code: https://gist.github.com/3123593

Now we can write code like golang:
--
interface IFoo {
    void foo(int a, string b, float c);
}

struct Foo {
    void foo(int a, string b, float c) {
        writeln("Foo.foo: ", a, ", ", b, ", ", c);
    }
}

struct FooFoo {
    void foo(int a, string b, float c) {
        writeln("FooFoo.foo: ", a, ", ", b, ", ", c);
    }
}

GoInterface!(IFoo) f = new Foo;
f.foo(3, "abc", 2.2);

f = new FooFoo;
f.foo(5, "def", 7.7);
--

It is also very naive, does not support some features, like out/ref
parameters, free functions *[1]* and so on. The biggest problem is downcast
not supported. In golang, we can write code like*[2]*:
--
var p IWriter = NewB(10)
p2, ok := p.(IReadWriter)
--

Seems [p.(IReadWriter)] dynamically build a virtual table *[3]*,because the
type of "p" is IWriter, it is *smaller* than IReadWriter, the cast
operation must search methods and build vtbl at run time.

In D, GoInterface(T).opAssign!(V)(V v) can build a rich runtime information
to *V* if we need. But if *V* is interface or base class, the type
information not complete. So, seems like I need runtime reflection? and how
can I do this in D? I did not find any useful information in the TypeInfo*.

------
[1] free functions support, e.g.
--
interface IFoo {
    void foo(int a, string b, float c);
}
void foo(int self, int a, string b, float c) {
    writefln("...");
}

GoInterface!(int) p = 1;
p.foo(4, "ccc", 6.6);
--
In theory no problem.

[2] example from
https://github.com/xushiwei/gobook/blob/master/dive-into/interface/03/interface.go
[3] /path/of/go/src/pkg/runtime/iface.c: static Itab* itab(InterfaceType
*inter, Type *type, int32 canfail)


Best regards,

-- Li Jie
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.puremagic.com/pipermail/digitalmars-d/attachments/20120717/2c036bd1/attachment.html>


More information about the Digitalmars-d mailing list