www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Address problem

reply Gheorghe Gabriel <knoppy273 live.com> writes:
Hi,
---------------------------------------------------
interface I { }

I[string] i;

class C : I {
     this() {
         i["s"] = this;
         foreach (_i; i) {
             writeln(&_i);
         }
         foreach (ref _i; i) {
             writeln(&_i);
         }
     }
}

void main() {
     C c = new C;
     writeln(&c);
}
---------------------------------------------------
output:
19FDD8
2802028
21FE58
---------------------------------------------------
I need that I["s"] to have the same address like c.
Oct 24 2017
parent =?UTF-8?Q?Ali_=c3=87ehreli?= <acehreli yahoo.com> writes:
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
Oct 24 2017