Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing objects memory address in ruby..?

Tags:

ruby

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.

like image 754
levirg Avatar asked Mar 08 '10 15:03

levirg


People also ask

How do I find the memory address in Ruby?

"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."

What is object id in Ruby?

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.

Can I get a Python object from its memory address?

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.


1 Answers

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.

like image 86
d3vin Avatar answered Sep 20 '22 19:09

d3vin