Address problem

Ali Çehreli acehreli at yahoo.com
Tue Oct 24 18:11:21 UTC 2017


On 10/24/2017 10:47 AM, Gheorghe Gabriel wrote:

 >              writeln(&_i);

That's the address of the local variable _i. You can think of class (and 
interface) variables as pointers to class objects.

 > I need that I["s"] to have the same address like c.

The way to get the address of the actual object is to cast the class 
variable to void*. Here is your program with that change:

import std.stdio;

interface I { }

I[string] i;

class C : I {
     this() {
         i["s"] = this;
         foreach (_i; i) {
             writeln("value ", cast(void*)_i);
         }
         foreach (ref _i; i) {
             writeln("ref   ", cast(void*)_i);
         }
     }
}

void main() {
     C c = new C;
     writeln("main  ", cast(void*)c);
     assert(c is i["s"]);
}

Sample output for a 64-bit build:

value 7FCE3EB23110
ref   7FCE3EB23110
main  7FCE3EB23100

The reason why main's is different is because c is an object as opposed 
to an interface. Apparently, it has extra 16 bytes of stuff before the 
interface part.

Note the last line of main. Perhaps all you really need to do is to use 
the 'is' operator, which already takes care of such address calculations.

Ali



More information about the Digitalmars-d-learn mailing list