Say I have a variable:
let a = ref 3 in magic_code
Magic_code should print the address in memory that is stored in a
. Is there something like that? I googled this but nothing came up...
Say I have a variable:
let a = ref 3 in magic_code
Magic_code should print the address in memory that is stored in a
. Is there something like that? I googled this but nothing came up...
This should work:
let a = ref 3 in
let address = 2*(Obj.magic a) in
Printf.printf "%d" address;;
OCaml distinguishes between heap pointers and integers using the least significant bit of a word, 0 for pointers and 1 for integers (see this chapter in Real World OCaml).
Obj.magic
is a function of type 'a -> 'b
that lets you bypass typing (i.e. arbitrarily "cast"). If you force OCaml to interpret the reference as an int
by unsafely casting it via Obj.magic
, the value you get is the address shifted right by one bit. To obtain the actual memory address, you need to shift it back left by 1 bit, i.e. double the value.
Also see this answer.