C extension: How to get a block passed to a method?

Hi, let's imagine the following Ruby code:

   my_method("hello") {
     puts "bye"
   }

In pure Ruby the method definition would be:

    def my_method string, &block
      puts string
      block.call
    end

Now the question is: how to do the same at Ruby C level? I assume the
following will not work:

  rb_define_module_function(mModule, "my_method", my_method, 2);

since:

  method(:my_method).arity
  => 1

So how can I get the block given to a method in C code?

Thanks a lot.

···

--
Iñaki Baz Castillo
<ibc@aliax.net>

<snip>

If I understand your question correctly, you're asking how to invoke a
block that's passed into a method written as a native extension. Is
that correct?

In a Ruby extension written in C, you would use something like this:

// if a block was passed to this method then invoke it
if(rb_block_given_p())
  {
    rb_yield(/* args */);
  }

rb_block_given_p() returns true if a code block was passed into the
method being processed. And rb_yield invokes that block with the
provided arguments (you can pass 0 or more args to the rb_yield).

HTH.

···

On Wed, Apr 18, 2012 at 12:34 PM, Iñaki Baz Castillo <ibc@aliax.net> wrote:

--
Darryl L. Pierce <mcpierce@gmail.com>
Visit the Infobahn Offramp: <http://mcpierce.multiply.com>
"Bury me next to my wife. Nothing too fancy..." - Ulysses S. Grant

If rb_block_given_p returns true you can use rb_block_proc to get the
VALUE for the proc.

HTH,
Ammar

···

On Wed, Apr 18, 2012 at 7:34 PM, Iñaki Baz Castillo <ibc@aliax.net> wrote:

So how can I get the block given to a method in C code?

to get it as a VALUE use
rb_block_proc()

···

--
Posted via http://www.ruby-forum.com/.

Not exactly. What I need is not to execute the passed block, but to
*get* it as a VALUE object to store it somewhere in my C code and so.

···

2012/4/18 Darryl L. Pierce <mcpierce@gmail.com>:

If I understand your question correctly, you're asking how to invoke a
block that's passed into a method written as a native extension. Is
that correct?

--
Iñaki Baz Castillo
<ibc@aliax.net>

Thanks a lot!

···

2012/4/18 Ammar Ali <ammarabuali@gmail.com>:

On Wed, Apr 18, 2012 at 7:34 PM, Iñaki Baz Castillo <ibc@aliax.net> wrote:

So how can I get the block given to a method in C code?

If rb_block_given_p returns true you can use rb_block_proc to get the
VALUE for the proc.

--
Iñaki Baz Castillo
<ibc@aliax.net>