Using pack/unpack to go from string to address and back to s

Hi all,

Is there a way, given a pointer address, to get back to the original
object? I’m thinking specifically of strings here.

irb(main):006:0> str = “hello”
=> “hello”
irb(main):007:0> addr = [str].pack(‘p*’).unpack(‘l’)
=> [43397704]

Is there a way to go from that address back to “hello”? You can’t
simply reverse it:

irb(main):025:0> addr.pack(‘l’).unpack(‘p*’)
ArgumentError: no associated pointer

It was pointed out to me that Ruby uses rb_str_associate and
rb_str_associated behind the scenes with regards to pack(‘p’), but I’m
also wondering about addresses for strings that weren’t obtained via
pack(‘p*’).

Or is this simply impossible?

Thanks,

Dan

This communication is the property of Qwest and may contain confidential
or
privileged information. Unauthorized use of this communication is
strictly
prohibited and may be unlawful. If you have received this communication
in error, please immediately notify the sender by reply e-mail and
destroy
all copies of the communication and any attachments.

Hi,

At Wed, 21 Jun 2006 23:22:17 +0900,
Berger, Daniel wrote in [ruby-talk:198375]:

It was pointed out to me that Ruby uses rb_str_associate and
rb_str_associated behind the scenes with regards to pack(‘p’), but I’m
also wondering about addresses for strings that weren’t obtained via
pack(‘p*’).

Or is this simply impossible?

It’s disallowed. If it were possible, you could get an illegal
“String.” For instance:

[1].pack(‘l’).unpack(‘p*’)

[email protected] wrote:

Or is this simply impossible?

It’s disallowed. If it were possible, you could get an illegal
“String.” For instance:

[1].pack(‘l’).unpack(‘p*’)

Would it be possible to make an exception for strings (char pointers)?
Or is there no way to determine the type of underlying object in time?

Dan

Hi,

At Fri, 23 Jun 2006 02:06:26 +0900,
Daniel B. wrote in [ruby-talk:198559]:

It’s disallowed. If it were possible, you could get an illegal
“String.” For instance:

[1].pack(‘l’).unpack(‘p*’)

Would it be possible to make an exception for strings (char pointers)?

How can you tell if it is a valid pointer? Use DL::Ptr if you
really sure, at your own risk.

Or is there no way to determine the type of underlying object in time?

Basically, no way to determine what a bare memory chunk is.

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs