adding methods to classes via C

G

Geert Fannes

------_=_NextPart_001_01C56C26.4C0FD588
Content-Type: text/plain;
charset="US-ASCII"
Content-Transfer-Encoding: quoted-printable

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.

=20

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

#this is the base class

class A

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

end

=20

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

class B < A

require('f.so')

end

=20

B.new.f

=20

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

#include "ruby.h"

=20

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

=20

VALUE cA,cB;

void Init_f(){

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

cA=3Drb_define_class("A",rb_cObject);

cB=3Drb_define_class("B",cA);

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

cB=3Drb_gv_get("B");

=20

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

=20

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?

=20

Greetings,

Geert Fannes.


------_=_NextPart_001_01C56C26.4C0FD588--
 
G

Guillaume Cottenceau

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

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

--=20
Guillaume Cottenceau - http://zarb.org/~gc/
 

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

Forum statistics

Threads
473,995
Messages
2,570,236
Members
46,822
Latest member
israfaceZa

Latest Threads

Top