Stefano Crocco
1/24/2007 4:01:00 PM
Alle 16:25, mercoledì 24 gennaio 2007, Shea Martin ha scritto:
> Shea Martin wrote:
> > Thanks, that worked great. How do I do I define a class method? Doesn't
> > seem to be in ruby book.
> > ~S
>
> Also, I can't seem to figure out how to pass ARGV to my script. I tried
> setting the global AGV before running, but it gets reset when I start.
>
> ~S
You should use the ruby_options C function.
To define a class method, you should first define a class. This is done using
the rb_define_class function. It takes two parameters, the name of the class
(as a char*) and the superclass (as a VALUE, not its name). For instance, if
you want to define the class MyClass, as a subclass of Object, you'd do:
rb_define_class("MyClass", rb_cObject);
rb_cObject is a C global variable of type VALUE which corresponds to the ruby
Object class. rb_define_class returns a VALUE corresponding to the new class.
With it, you can define both instance methods and class methods.
To define a class method you should use rb_define_module_function, while to
define an instance method, you'd use the rb_define_method function. They both
takes four arguments: the class or module (the value returned by
rb_define_class, for instance), the name of the method, a pointer to the C
function which implements the method and the number of arguments this C
function takes (including the self argument).
A complete example (again, untested):
static VALUE _class_method(VALUE self, VALUE arg){
//Do something here and return a VALUE or Qnil
}
static VALUE _instance_method(VALUE self){
//Do something else here and return a VALUE or Qnil
}
void InitMyClass(){
VALUE cls=rb_define_class("MyClass", rb_cObject);
rb_define_module_function(cls, "a_class_method", _class_method, 2);
rb_define_method(cls, "an_instance_method", _instance_method, 1);
}
Stefano