hoodwink.d enhanced
RSS
2.0
XHTML
1.0

RedHanded

Wrapping a C Function as a Block #

by why in bits

I had previously been using rb_iterate and a call to Proc.new to build a block in C. But that takes two function calls while the undocumented rb_proc_new is just one.

 require 'rubygems'
 require 'inline'

 module Kernel
   inline do |ext|
     ext.prefix %{
       static VALUE sum(VALUE args)
       {
         return rb_funcall(rb_ary_entry(args, 0), rb_intern("+"), 1, 
           rb_ary_entry(args, 1));
         return Qnil;
       }
     }
     ext.c %{
       VALUE sum_block()
       {
         return rb_proc_new(sum, 0);
       }
     }
   end
 end

 p sum_block[13, 2]
 p (0..20).inject(0, &sum_block)

Most of the time rb_iterate is what you need. But, you know, in case you actually want a Proc object.

said on 19 Jan 2007 at 11:57

_why’s blog posts make me happy :)

said on 19 Jan 2007 at 12:40

RubyInline is really cool.

said on 19 Jan 2007 at 13:04

zimbatm: What about what makes me happy?? I’ve been waiting sooo patiently for rwm!!

FlashHater: Yes.

said on 19 Jan 2007 at 15:47

argh. this comment system bites… keeps ignoring my post w/o a reason.

why, change c_raw to prefix unless you intend sum to be a public method as well.

said on 19 Jan 2007 at 16:19

Oh, okay, just like that.

said on 19 Jan 2007 at 16:27

does that mean you can write assembly in c in ruby?

11 Jul 2010 at 20:50

* do fancy stuff in your comment.

PREVIEW PANE