Is there any way in Ruby to get the memory address of objects?
(i = 5)
Is it possible to get the memory address of that object 5
?
I have been trying to get this over some time.
"You can get the actual pointer value of an object by taking the object id, and doing a bitwise shift to the left. This will give you the pointer (or memory location) of the ruby object in memory."
For every object, Ruby offers a method called object_id. You guessed it, this represents a random id for the specific object. This value is a reference of the address in memory where the object is store. Every object has a unique object id that will not change throughout the life of this object.
Now that we have addresses, we can get value/python objects again from the memory address using ctypes module. where, memeory_address is the memory address of the variable. value is the method which is used to extract a value.
Yes.
From "Fiddling with Ruby’s Fiddle":
"You can get the actual pointer value of an object by taking the object id, and doing a bitwise shift to the left. This will give you the pointer (or memory location) of the ruby object in memory."
Using your example of i = 5
it could be done like so:
i = 5
i_ptr_int = i.object_id << 1
=> 22
"In Ruby, why does inspect() print out some kind of object id which is different from what object_id() gives?" has more info about object_id
, including a brief introduction to the C source underlying the implementation which you might find helpful.
Take a look at "Fiddle" for some other cool things you can do.
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