Forum: Ruby Re: Shortcut for .pack("p*").unpack("l").first ?

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
F3b7b8756d0c7f71cc7460cc33aefaee?d=identicon&s=25 Berger, Daniel (Guest)
on 2006-05-03 18:57
(Received via mailing list)
> > If I want to get the underlying pointer address of a
> > Ruby string, I can do this:
>
> What do you want with a memory address in Ruby-land?  If
> you're in an extension then there's probably an easier way to
> get at the address.

Short answer: Win32API

strcmp1 = Win32API.new('msvcrt', 'strcmp', 'PP', 'I')
strcmp2 = Win32API.new('msvcrt', 'strcmp', 'LL', 'I')

str1 = "hello"
str2 = "hello"
str3 = "world"

addr1 = [str1].pack("p*").unpack("l").first
addr2 = [str2].pack("p*").unpack("l").first
addr3 = [str3].pack("p*").unpack("l").first

# Using strings
strcmp1.call(str1, str2) # 0
strcmp1.call(str1, str3) # -1

# Using string addresses
strcmp2.call(addr1, addr2) # 0
strcmp2.call(addr1, addr3) # -1

I suppose I could stop whining and just extend the String class. :)

class String
   def ptr
      [self].pack("p*").unpack("l").first
   end
end

This might be useful for Ruby/DL as well.

Regards,

Dan

PS - Many thanks to Heesob for teaching me some of these things lately.
:)


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.
E0d864d9677f3c1482a20152b7cac0e2?d=identicon&s=25 Robert Klemme (Guest)
on 2006-05-03 18:57
(Received via mailing list)
2006/5/1, Berger, Daniel <Daniel.Berger@qwest.com>:
> > What do you want with a memory address in Ruby-land?  If
> > you're in an extension then there's probably an easier way to
> > get at the address.
>
> Short answer: Win32API

Here you got me convinced.

>
> # Using strings
> strcmp1.call(str1, str2) # 0
> strcmp1.call(str1, str3) # -1
>
> # Using string addresses
> strcmp2.call(addr1, addr2) # 0
> strcmp2.call(addr1, addr3) # -1

Now you lost me again: if you can use a string as well as a pointer
then why bother to use the pointer? Are there places where you cannot
do that?

> I suppose I could stop whining and just extend the String class. :)

That's definitively an option. :-))

> class String
>    def ptr
>       [self].pack("p*").unpack("l").first
>    end
> end

Just a thought: does it make sense to raise an exception or print a
warning if the string is not frozen?  Otherwise the address could
point into limbo...

Cheers

robert
This topic is locked and can not be replied to.