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

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.
0f1f17ba297242e9d3c86d4cc0a6ea85?d=identicon&s=25 Iñaki Baz Castillo (Guest)
on 2009-04-03 17:47
(Received via mailing list)
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.
8b4249ca3bb8c123da9f7aca63a652e1?d=identicon&s=25 Andre Nathan (Guest)
on 2009-04-03 18:04
(Received via mailing list)
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

HTH,
Andre
0f1f17ba297242e9d3c86d4cc0a6ea85?d=identicon&s=25 Iñaki Baz Castillo (Guest)
on 2009-04-03 18:29
(Received via mailing list)
2009/4/3 Andre Nathan <andre@digirati.com.br>:
>    return Qnil;
>
> class Foo; end
> require 'foo'
> Foo.new.foo


Thanks a lot!
58479f76374a3ba3c69b9804163f39f4?d=identicon&s=25 Eric Hodel (Guest)
on 2009-04-03 22:40
(Received via mailing list)
On Apr 3, 2009, at 09:03, Andre Nathan wrote:
>    return Qnil;
> }
>
> void
> Init_foo(void)
> {
>    VALUE klass = rb_const_get(rb_cObject, rb_intern("Foo"));
>    rb_define_method(klass, "foo", rb_foo, 0);
> }

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
This topic is locked and can not be replied to.