Add a method as C extension to a class defined in Ruby

Hi, in case I want to add a method (using C) for a class I've created
in pure Ruby, must I also create the class in C?

If not, how to fill MY_CLASS here?:

  rb_define_method(MY_CLASS, "my_method", my_method, arg_count);

Thanks.

···

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

Something like this should work:

static VALUE
rb_foo(VALUE self)
{
    rb_p(INT2FIX(42));
    return Qnil;
}

void
Init_foo(void)
{
    VALUE klass = rb_const_get(rb_cObject, rb_intern("Foo"));
    rb_define_method(klass, "foo", rb_foo, 0);
}

Then you should be able to do

class Foo; end
require 'foo'
Foo.new.foo

HTH,
Andre

···

On Sat, 2009-04-04 at 00:45 +0900, Iñaki Baz Castillo wrote:

Hi, in case I want to add a method (using C) for a class I've created
in pure Ruby, must I also create the class in C?

Thanks a lot!

···

2009/4/3 Andre Nathan <andre@digirati.com.br>:

On Sat, 2009-04-04 at 00:45 +0900, Iñaki Baz Castillo wrote:

Hi, in case I want to add a method (using C) for a class I've created
in pure Ruby, must I also create the class in C?

Something like this should work:

static VALUE
rb_foo(VALUE self)
{
rb_p(INT2FIX(42));
return Qnil;
}

void
Init_foo(void)
{
VALUE klass = rb_const_get(rb_cObject, rb_intern("Foo"));
rb_define_method(klass, "foo", rb_foo, 0);
}

Then you should be able to do

class Foo; end
require 'foo'
Foo.new.foo

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

It's better with RubyInline:

require 'rubygems'
require 'inline'

class Foo
   inline :C do |builder|
     builder.c <<-C
       void foo() {
         rb_p(INT2FIX(42));
       }
     C
   end
end

Foo.new.foo

···

On Apr 3, 2009, at 09:03, Andre Nathan wrote:

On Sat, 2009-04-04 at 00:45 +0900, Iñaki Baz Castillo wrote:

Hi, in case I want to add a method (using C) for a class I've created
in pure Ruby, must I also create the class in C?

Something like this should work:

static VALUE
rb_foo(VALUE self)
{
   rb_p(INT2FIX(42));
   return Qnil;
}

void
Init_foo(void)
{
   VALUE klass = rb_const_get(rb_cObject, rb_intern("Foo"));
   rb_define_method(klass, "foo", rb_foo, 0);
}