calling ruby methods in C

C

Charles Mills

I have a question about what is the best way to call Ruby methods which
are implemented in C from C.
The two basic ways I see are :
1) using one of the rb_funcall[0-9] C functions.
2) calling the actual C function.
For example if I am pushing objects onto an array in my C code I could do
this:

VALUE arr = rb_ary_new2(some_num);
VALUE some_obj = ...;
rb_ary_push(arr, some_obj);

or this:

VALUE arr = rb_ary_new2(some_num);
VALUE some_obj = ...;
rb_funcall(arr, rb_intern("push"), 1, some_obj);

So my main question is:
should you only call the C function defined in "ruby.h" directly (not
using rb_funcall) in you extensions or is it OK to call the C functions
defined in "intern.h" directly as well?
thoughts:
I assume "ruby.h" and "intern.h" are seperated for a reason and you should
limit you C code to using stuff from "ruby.h" only, ie don't include
"intern.h" in your extensions. One reason being that if you don't use
rb_funcall or a similar function no OO dispatch will take place. So if
someone overrides "push" and you call push using rb_ary_push you won't be
calling the version of "push" you should be.
Any opinions on this?

-Charlie
 
N

nobu.nokada

Hi,

At Tue, 20 Jan 2004 01:53:02 +0900,
Charles said:
Looks like this question was mostly answered by this post
http://blade.nagaokaut.ac.jp/cgi-bin/scat.rb/ruby/ruby-talk/1807
but the question still remains is it better to use rb_funcall to invoke
the Ruby method or call the corresponding C function directly?

For an instance made in same function, direct call would be
enough. Otherwise, for an instance given from others, you may
want to consider the case it is a subclass.
 

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,776
Messages
2,569,603
Members
45,197
Latest member
Sean29G025

Latest Threads

Top