Sending an immutable object to a thread

Ali Çehreli via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Fri Jul 24 11:02:57 PDT 2015


On 07/23/2015 06:48 AM, Frank Pagliughi wrote:

 > So, passing a pointer to a stack-based reference from one thread is
 > another is not necessarily a good thing to do, as the original reference
 > might disappear while the thread is using it.

Right.

 > Is there a way to get the address of the actual heap object from a class
 > reference?

It is possible by casting the reference to a pointer type:

import std.stdio;

class B
{
     int i;
     this(int i) { this.i = i; }
}

class D : B
{
     int j;
     this (int j) {
         super(j);
         this.j = j + 1;
     }
}

void main()
{
     auto r = new D(42);
     writefln("Address of reference: %s", &r);
     writefln("Address of object   : %s", cast(void*)r);
     writefln("Address of i        : %s", &r.i);
     writefln("Address of j        : %s", &r.j);

     auto p = cast(void*)r;
     auto r2 = cast(D)p;
     writefln("i through another reference: %s", r2.i);
     writefln("j through another reference: %s", r2.j);
}

Although the example casts to void*, ubyte* and others are possible as 
well, and casting back to the correct class type seems to work:

Address of reference: 7FFFCB137580
Address of object   : 7FFCB9407520
Address of i        : 7FFCB9407530
Address of j        : 7FFCB9407534
i through another reference: 42
j through another reference: 43

Ali



More information about the Digitalmars-d-learn mailing list