c extension, classes and subclasses

R

Rolando Abarca

I have a few doubts about how the init mechanism in ruby1.9 (I'm
working with it right now) works. I have a some classes and
subclasses, all defined inside a ruby extension, the base class
defines it's +new+ method like this:

rb_define_singleton_method(rb_cMyClass, "new", rb_cMyClass_s_new, -1);

This is the +new+ method:

VALUE rb_cMyClass_s_new(int argc, VALUE *argv, VALUE klass) {
void *node;
my_struct *ptr;
...
VALUE obj = Data_Make_Struct(klass, my_struct, 0, custom_free, ptr);
rb_obj_call_init(obj, argc, argv);
return obj;
}

and every subclass defines a +new+ method just like that. The thing is:
Does rb_obj_call_init calls the superclass' new method?
Is this The Right Way(tm) to define/initialise classes and subclasses?

Thanks!
 
R

Roger Pack

and every subclass defines a +new+ method just like that. The thing is:

not if it's been redefined by the child class, I don't think.
Does rb_obj_call_init calls the superclass' new method?
Is this The Right Way(tm) to define/initialise classes and subclasses?

I think so. Try it out and see if it works :)
=r [maybe asking core might be helpful, too, though...maybe not].
 
K

KUBO Takehiro

Hi,

I have a few doubts about how the init mechanism in ruby1.9 (I'm working
with it right now) works. I have a some classes and subclasses, all defined
inside a ruby extension, the base class defines it's +new+ method like this:

rb_define_singleton_method(rb_cMyClass, "new", rb_cMyClass_s_new, -1);

Defining a singleton method "new" is old style which had been used for
ruby 1.6 or before.
Does rb_obj_call_init calls the superclass' new method?

No, rb_obj_call_init just calls the instance method 'initialize'.
Is this The Right Way(tm) to define/initialise classes and subclasses?

1. Register a function to allocate a memory region by
rb_define_alloc_func(rb_cMyClass, ...).
2. Define "initialize" method to initialize the memory region by
rb_define_method(rb_cMyClass, "initialize", ...).
It is called by MyClass.new after allocating the memory.
3. Define "initialize_copy" method also for MyClass#dup and
MyClass#clone. They don't call "initialize".
 

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,755
Messages
2,569,534
Members
45,007
Latest member
obedient dusk

Latest Threads

Top