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

  • Thread starter Iñaki Baz Castillo
  • Start date
I

Iñaki Baz Castillo

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.


--=20
I=C3=B1aki Baz Castillo
<[email protected]>
 
A

Andre Nathan

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
 
I

Iñaki Baz Castillo

2009/4/3 Andre Nathan said:
Something like this should work:

static VALUE
rb_foo(VALUE self)
{
=C2=A0 =C2=A0rb_p(INT2FIX(42));
=C2=A0 =C2=A0return Qnil;
}

void
Init_foo(void)
{
=C2=A0 =C2=A0VALUE klass =3D rb_const_get(rb_cObject, rb_intern("Foo"));
=C2=A0 =C2=A0rb_define_method(klass, "foo", rb_foo, 0);
}

Then you should be able to do

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


Thanks a lot!

--=20
I=C3=B1aki Baz Castillo
<[email protected]>
 
E

Eric Hodel

Something like this should work:

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

void
Init_foo(void)
{
VALUE klass =3D 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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,968
Messages
2,570,150
Members
46,697
Latest member
AugustNabo

Latest Threads

Top