From: ptkwt@...1.aracnet.com (Phil Tomson) Date: 2002-09-11T08:15:57+09:00 Subject: Re: RubyInline 1.0.4 Released! (fwd) In article , Pat Eyler wrote: >On Wed, 11 Sep 2002, JamesBritt wrote: > >> > >> > RubyInline 1.0.4 has been released! >> > >> > Ruby Inline is my quick attempt to create an analog to Perl's >> > Inline::C. The ruby version isn't near as feature-full as the perl >> > version, but it is neat! >> >> Um, what does Perl's Inline::C do? >> > >the Inline:: modules for Perl, Python, and Ruby allow you to include >non-native code inside a script. here's an example of Perl's Inline::Ruby > > use Inline Ruby; > > $obj = Iterator->new(1, "2", [3, 4], {5 => 6}); > $obj->iter(\&my_iter)->each; > > sub iter { > use Data::Dumper; > print Dumper \@_; > } > > __END__ > __Ruby__ > > class Iterator > def initialize(*elements) > @elements = elements > end > def each > for i in @elements > yield i > end > end > end > I was shown this example last night at our PDX.rb meeting... I found it hard to believe that you could pass a Perl subroutine reference to a Ruby iterator and that it would work - but it does. Cool. Twisted, but cool. > > >maybe someone would like to post a code sample of Inline::C from ruby? > Here's the code from the example that comes with RubyInline: #!/usr/local/bin/ruby -w require "inline" class MyTest include Inline def factorial(n) f = 1 n.downto(1) { |x| f = f * x } f end def fastfact(*args) #what follows is C code: inline args, <<-END int i, f=1; for (i = FIX2INT(argv[0]); i >= 1; i--) { f = f * i; } return INT2FIX(f); END #end of C code end end t = MyTest.new() max = 1000000 puts "RubyInline #{Inline::VERSION}" if ARGV.length == 0 then type = "Inline" tstart = Time.now (1..max).each { |n| r = t.fastfact(5); if r != 120 then puts "ACK! - #{r}"; end } tend = Time.now else type = "Native" tstart = Time.now (1..max).each { |n| r = t.factorial(5); if r != 120 then puts "ACK! - #{r}"; end } tend = Time.now end total = tend - tstart avg = total / max printf "Type = #{type}, Iter = #{max}, time = %.8f sec, %.8f sec / iter\n", total, avg ###end of example So the C code in the MyTest#fastfact method is converted to Ruby-C code and compiled into a shared library with gcc. The .so file is stored in the /tmp directory so that on subsequent runs the C code doesn't need to be recompiled. Is this similar to what Python's Boost tool does? Perl has Inline modules available for several languages including Ruby (as shown above by Pat). Now it might be nice to have a RubyInline::Perl module so people can make use of legacy Perl code in their Ruby apps. Phil