13

Simple question but I didn't see any answers on the internet. So, how can I get address of an object in Kotlin?

mr.icetea
  • 2,607
  • 3
  • 24
  • 42
  • what do you mean by "address"? – Roland Jan 08 '19 at 10:08
  • @Roland I mean the object address in the memory – mr.icetea Jan 08 '19 at 10:09
  • In general, you can't.  Why would you want to?  What are you trying to achieve? – gidds Jan 08 '19 at 10:11
  • @gidds In some cases I want to track my object in memory for debugging purpose – mr.icetea Jan 08 '19 at 10:12
  • You may want to read about memory addresses and Java... you should not access the memory address of objects directly... Some interesting questions about that: [Memory address of variables in Java](https://stackoverflow.com/questions/1961146/memory-address-of-variables-in-java), [How to get address of a Java Object?](https://stackoverflow.com/questions/1360826/how-to-get-address-of-a-java-object), [Is there a way to get a reference address?](https://stackoverflow.com/questions/8820164/is-there-a-way-to-get-a-reference-address) and just follow the duplicates from there on ;-) – Roland Jan 08 '19 at 10:15
  • @Roland thank for your references – mr.icetea Jan 08 '19 at 10:27

2 Answers2

33

To identify an object during debugging, use System.identityHashCode().

The address of an object can't be obtained on Kotlin/JVM, and it can also change as GC runs, so it can't be used to identify an object.

yole
  • 92,896
  • 20
  • 260
  • 197
2

Kotlin in the JVM does not support pointers and so (apart from some jiggery-pokery with the sun.misc.Unsafe class) there is no way to obtain a variable's address.

However, Kotlin/Native (at least back in January 2018) does support pointers to enable it to interoperate with C code. The following program shows how to obtain the address of a variable which has been allocated on the native heap. It does not appear to be possible to allocate a variable at a particular address.

// Kotlin Native v0.5

import kotlinx.cinterop.*

fun main(args: Array<String>) {
    val intVar = nativeHeap.alloc<IntVar>()
    intVar.value = 42
    with(intVar) { println("Value is $value, address is $rawPtr") }
    nativeHeap.free(intVar)
}

results in:

Value is 42, address is 0xc149f0
Yolgie
  • 268
  • 3
  • 16
  • If you really want the address of an object inside the JVM please refer to [How can I get the memory location of a object in java?](https://stackoverflow.com/questions/7060215/how-can-i-get-the-memory-location-of-a-object-in-java) or [Is there a way to get a reference address?](https://stackoverflow.com/questions/8820164/is-there-a-way-to-get-a-reference-address) – Yolgie Jan 08 '19 at 10:15