www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - How to get the address of an instance of a class

reply dokutoku <3729541-dokutoku users.noreply.gitlab.com> writes:
I wrote the following code to get the address of a class 
instance, but it doesn't work.
Please let me know if there is a way to write it to work properly.

private import std;

```
class C
{
	C* this_pointer()
	{
		return this;
	}
}

void main()
{
	C Z = new C();
	writeln(&Z == Z.this_pointer());
}
```
Sep 25 2019
parent Tobias Pankrath <tobias pankrath.net> writes:
On Wednesday, 25 September 2019 at 17:32:25 UTC, dokutoku wrote:
 I wrote the following code to get the address of a class 
 instance, but it doesn't work.
 Please let me know if there is a way to write it to work 
 properly.

 private import std;

 ```
 class C
 {
 	C* this_pointer()
 	{
 		return this;
 	}
 }

 void main()
 {
 	C Z = new C();
 	writeln(&Z == Z.this_pointer());
 }
 ```
Classes are always references. I think you can just cast 'Z' to void* to get the address. Conversely &Z should be an address on the stack.
Sep 25 2019