daz wrote:
> Austin McDonald wrote:
> 
>>Hi, I'm attempting to transfer some intensive functions from Ruby to C,
>>but I'd like to put as little of my code in C as possible.  So, I'm
>>trying to access a class defined entirely in Ruby from my C code.
>>Specifically, I need to create an instance of this class (called
>>Population) and access some of its methods.  A few questions about this:
>>
>>1) Do the functions I need to use have to be implemented in C as well,
>>or can I access their "ruby version" using some C functions?  What C
>>functions do I need to use to do this?
>>
> 
> 
> Seemless beauty is what you'll find :-)
> Define an empty class (if its name is known) in the Init_foo part of
> your extension - look at any other extension to get clues (rb_define_class).
> 
> Reopen your class (looks the same as a class definition) and define
> your methods inside it (all in Ruby):
> 
> class Foo
>   def a
>     # whatever
>   end
> 
>   def b
>   end
> end
> 
> Call them from C using the rb_funcall family.

This isn't going to help much, if at all, with the speed of these calls, 
since it still goes thru the usual method lookup. Maybe that's ok, if 
the bottleneck is not these calls, but the code around them.

If you want to avoid the overhead of method calls, you have to trade 
away the flexibility of method lookup. The ruby source has many nice 
models for doing this. For instance, the method Array#push (in array.c) 
is callable from C code in (at least) two ways:

   ID id_push = rb_intern("push");
   rb_funcall(ary, id_push, 1, item);

and

   rb_ary_push(ary, item);

The former goes thru the usual lookup. The latter skips directly to the 
C function which implements push.

If you want objects of your class to be efficiently accessible from C, 
you may also want to use the DATA type, so that you don't have to look 
up instance variables, but can directly access the underlying struct. 
That's no longera class defined entirely in ruby, though.