[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.ruby

adding methods to classes via C

Geert Fannes

6/8/2005 12:34:00 PM

Hello,

for performance reasons, I have to add C-implemented methods to my
classes. This works fine, but I wonder if there exist more elegant
techniques for extending inherited classes. The code hereunder indicates
what I mean. The ruby file defines the class A and method A#f (which
writes out "A#f"), and the class B, which inherits from A, but B#f is
not defined. My goal is to define B#f in a C-file. My question has to do
with how I can get the class variable cB in an elegant way.



******the Ruby file******

#this is the base class

class A

def f() puts('A#f') end

end



#B inherits from A and I want to write a C-method for B#f

class B < A

require('f.so')

end



B.new.f



******the C file******

#include "ruby.h"



VALUE f0(VALUE self){printf("B#f");return self;}



VALUE cA,cB;

void Init_f(){

//correct: results into writing out "B#f"

cA=rb_define_class("A",rb_cObject);

cB=rb_define_class("B",cA);

//wrong: results into writing out "A#f"

cB=rb_gv_get("B");



rb_define_method(cB,"f",f0,0);}



The two lines after the "correct" comment gives the correct result and
writes out "B#f", but when I use the single line after the "wrong"
comment, the method A#f is called when ruby executes B.new.f(), which
writes out "A#f". In this problem, it is still feasible to follow the
whole inheritance path to get the correct cB value since B only inherits
from A, but this becomes more of a problem when using more complex
inheritance structures. Even more, I guess it should not matter if I
modify something to the inheritance structure (unless my C-function uses
some of the inherited classes), so this is some sort of
inheritance-structure duplication that leads to maintenance problems. Is
there a more elegant method to get the class variable?



Greetings,

Geert Fannes.

1 Answer

Guillaume Cottenceau

6/9/2005 7:48:00 AM

0

On 6/8/05, Geert Fannes <Geert.Fannes@ikanconsulting.com> wrote:

[...]

> inheritance-structure duplication that leads to maintenance problems. Is
> there a more elegant method to get the class variable?

VALUE klass = rb_const_get(rb_cObject, rb_intern("B"));

--
Guillaume Cottenceau - http://zar...