c extension, classes and subclasses

View: New views
3 Messages — Rating Filter:   Alert me  

c extension, classes and subclasses

by Rolando Abarca-2 :: Rate this Message:

Reply to Author | View Threaded | Show Only this Message

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!
--
Rolando Abarca M.






Re: c extension, classes and subclasses

by rogerdpack :: Rate this Message:

Reply to Author | View Threaded | Show Only this Message


> 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].

--
Posted via http://www.ruby-forum.com/.


Re: c extension, classes and subclasses

by KUBO Takehiro :: Rate this Message:

Reply to Author | View Threaded | Show Only this Message

Hi,

On Fri, Jul 10, 2009 at 1:42 AM, Rolando Abarca<funkaster@...> wrote:
> 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".