Friday, July 11, 2008

Ruby C API - Classes I


To create a class:


VALUE rb_define_class("name", parent_class);
VALUE rb_define_class_under(module_or_class, "name", parent_class);


To create a method:

rb_define_method(class, "name", c_function, argc)

argc is the number of arguments of the function, not including the first parameter of the c_function which would be the instance variable. Default Parameters can be implemented by setting this number to negative. (-1 would mean variable number of parameters, -2 would create an array to store the arguments)

"name" is the name of the method in ruby, for setter methods you would add the = to the name just like in ruby ( ie "name=" ). The same with operator for the [] operator you will use the string "[]" or "[]=".

The format of a ruby function accepting a variable number of arguments (argc = -1) would be like this:


VALUE function( int argc, VALUE* args, VALUE instance );


argc is the number of arguments passed.
args is an array containing the arguments.
instance is the instance of the object.

The format for a ruby function accepting an array of arguments (argc = -2) :


VALUE function( VALUE instance, VALUE array_of_arguments);


To access instance variables you will use this two methods:


rb_iv_get(instance, "variable");
rb_iv_set(instance, "variable", new_value);


stay tuned for part II.

No comments: