www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Getting the address of the class object

reply =?UTF-8?B?QWxpIMOHZWhyZWxp?= <acehreli yahoo.com> writes:
Coming from C++, I wonder whether it is ever needed to get the address 
of the object? If so, how?

The & operator below produces the address of the class reference 
(variable). How about the class object?

class C
{}

void main()
{
     auto variable = new C;
     auto address = &variable;
}

Thank you,
Ali
Jan 11 2010
parent reply bearophile <bearophileHUGS lycos.com> writes:
Ali Çehreli Wrote:

 Coming from C++, I wonder whether it is ever needed to get the address 
 of the object? If so, how?
I've never had to do this in D. I think you can just cast the class reference to void* and then to the pointer you want, something like (untested): Foo f = new Foo; auto p = cast(something*)cast(void*)f; Bye, bearophile
Jan 11 2010
parent =?UTF-8?B?QWxpIMOHZWhyZWxp?= <acehreli yahoo.com> writes:
bearophile wrote:
 Ali Çehreli Wrote:
 
 Coming from C++, I wonder whether it is ever needed to get the address 
 of the object? If so, how?
I've never had to do this in D. I think you can just cast the class reference to void* and then to the pointer you want, something like (untested): Foo f = new Foo; auto p = cast(something*)cast(void*)f; Bye, bearophile
Thanks, Seems to do the trick: import std.cstream; class C {} void main() { auto variable0 = new C; auto variable1 = variable0; dout.writefln("&variable0 : ", &variable0); dout.writefln("&variable1 : ", &variable1); dout.writefln("cast cast 0: ", cast(C*)cast(void*)variable0); dout.writefln("cast cast 1: ", cast(C*)cast(void*)variable1); } Outputs: &variable0 : BFE65A30 &variable1 : BFE65A34 cast cast 0: C08E40 cast cast 1: C08E40 I trust that the last two are the address of the actual object. ;) Ali
Jan 11 2010