minimal object.d implementation that allows classes
Steven Schveighoffer
schveiguy at yahoo.com
Thu Dec 7 14:59:57 UTC 2017
On 12/7/17 9:45 AM, Jean-Louis Leroy wrote:
> On Thursday, 7 December 2017 at 13:08:09 UTC, Luís Marques wrote:
>> On Thursday, 7 December 2017 at 08:59:08 UTC, Wild wrote:
>>> You could modify the one I use for PowerNex[1]. It is a hacked
>>> version of Adam D. Ruppes
>>> minimal.zip. There are only a few imports for strlen,
>>> mem{set,move,cpy}, etc.
>>
>> This one seems to be the one for me. For instance, typeid(ClassName)
>> seems to work, which I need.
>>
>> For completeness, I had looked into minlibd but it didn't seemed
>> compatible with LDC and difficult for me to fix, IIRC. Regarding
>> Mike's question of what my use case is, I wanted my program to run in
>> webassembly/asmjs. Since druntime/phobos haven't been ported to that
>> target, I was being careful with my design to not depend on the
>> runtime, but then I found out I love the openmethods package. So I
>> decided to check if I could implement just enough of druntime to allow
>> a forked version of openmethods to work. As far as I can tell that's
>> feasible.
>
> I am currently trying to understand how the compiler and the runtime
> interact. ClassInfo contains a vtbl array whose ptr property is the same
> as the vptr found in an instance of that class. However, when I modify
> that pointer (e.g. by reserving 1000 more entries) and create a new
> instance, it still contains the old pointer. So it looks like the
> compiler sets the vptr without consulting the ClassInfo but somehow
> reflects it there. I'd appreciate if anybody can explain how it works,
> or sends me links to relevant info.
>
> Example:
>
> import std.stdio;
>
> class Foo {
> void foo() {}
> }
>
> void main() {
> auto oldPtr = Foo.classinfo.vtbl.ptr;
> Foo.classinfo.vtbl.reserve(1000);
> writeln(oldPtr != Foo.classinfo.vtbl.ptr); // true
> Object foo = new Foo();
> writeln(oldPtr == *cast(void***)foo); // true, alas
> }
>
The object is constructed here:
https://github.com/dlang/druntime/blob/master/src/rt/lifetime.d#L71
specifically, the vtbl is set when you blit the initializer array
(another piece of the TypeInfo) into the class object here:
https://github.com/dlang/druntime/blob/master/src/rt/lifetime.d#L115
So basically, the reason why it happens is because the pointer you are
changing is not the piece that actually is used to intialize the block.
On a side note however, you really shouldn't change data in a ClassInfo
at all, and probably the compiler shouldn't let you! This is static
readonly data, and changing this is I think even disallowed on some OSes.
Relevant source of how vtbls in D work:
https://dlang.org/spec/abi.html#classes
-Steve
More information about the Digitalmars-d
mailing list