Simple question but I didn't see any answers on the internet. So, how can I get address of an object in Kotlin?
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With