October 24, 2017 Address problem | ||||
---|---|---|---|---|
| ||||
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. |
October 24, 2017 Re: Address problem | ||||
---|---|---|---|---|
| ||||
Posted in reply to Gheorghe Gabriel | 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 |
Copyright © 1999-2021 by the D Language Foundation