Andrew Hunt writes: > > Hi all, > > Just a quick question -- is the following sequence the correct > way to create a Ruby object from C? > > NEWOBJ(obj, c-type) -- allocate memory for an object > OBJSETUP(obj, class, T_class); -- set appropriate flags > rb_obj_call_init(obj, argc, argv); -- call initialize Depends on what you want to do... AFAIK, this is the correct way to create an instance of a Ruby built-in class. But many of them offer also a instance creation function on C level, e.g. rb_float_new, rb_str_new2, rb_ary_new, ... They will deliver a ready-to-use instance without additional taxes ;-) But if you want to create an instance of an own class (e.g. a Ruby extension written by yourself), you should going this way: my_RFoo *foo; VALUE obj; obj = Data_Make_Struct(klass, my_RFoo, mark_foo, free, foo); rb_obj_call_init(obj, argc, argv); The function 'mark_foo' has to be written, if you store references to Ruby class instances within your my_RFoo structure. This function would be called during garbage collection by the GC to let you mark all instances still alive yet! If your my_RFoo realizes a kind of e.g. list, you would need such 'mark_foo' function. If you have no reference to other Ruby instances stored within your my_RFoo structure, you simply can pass a 0 (ZERO) instead. The 'free' function would be called by the GC if it has decided that the lifetime of your object has ended! Often a simple C 'free' is enough! But if you wants to deallocate memory you have allocated within the 'new' method, you have also provide an own deallocate function, and pass it to Data_Make_Struct. > > There was some discussion a while back on whether *every* class called > initialize or not, how did that end up? It would apper from the > current code that most of the built-in classes *do not* call > an initialize method. I think, we was not coming to a conclusion yet! *I* think, that rb_obj_call_init should be called every time during instance creation. But there may be some exceptions for classes like Fixnum, for example. This would make it simplier to derive a new class coded in Ruby from a parent class coded in C, IMHO. To simulate inheritance in C also, I moved the C structure creation into my initialize method. The class will be created in MyFoo::new, but the memory of the underlaying C data structure will be allocated in MyFoo.initialize. That has the advantage, that a child class of MyFoo, derived on C level, can allocate its own memory, and let MyFoo.initialize initialize it with the concerning data. > > Many thanks! > > /\ndy > ... \cle -- Clemens Hintze mailto: c.hintze / gmx.net