How to judge the type of an object which is passed as an argument from Ruby to C?

Hi,

I am writing some programs hybrid of ruby and C. Rat, Buffalo, and Ranch
are classes defined by me. Now in the Ruby program ranch.rb I pass an
object (say, a Rat object rato) as an argument to the method
“Ranch.new()”. Then Ranch.new(herder, role, rato) will invoke the
function “ranch_initialize()” in C program ranch.c. At this moment in
the body of the function “ranch_initialize()”, how should I judge/decide
the variable vsubject is a Rat object, or a Buffalo object, or a
String? The reason why I want to judge the type of the variable
vsubject is: if it’s a Rat object I will do A operation, if it’s a
Buffalo object I will do B operation, if it’s a String I will do C
operation. It’s like the function overloading for the parameter
vsubject. Please see part of the codes below.

ranch.rb:
rato = Rat.new(user, pass)
buffaloo = Buffalo.new(user, pass)
planto = “plant string”
rancho = Ranch.new(herder, role, rato)
#rancho = Ranch.new(herder, role, buffaloo)
#rancho = Ranch.new(herder, role, planto)

ranch.c:
static VALUE ranch_initialize(int argc, VALUE *argv, VALUE self)
{
VALUE vherder;
VALUE vrole;
VALUE vsubject;
rb_scan_args(argc, argv, “21”, &vherder, &vrole, &vsubject);
//Now how can I judge vsubject is a Rat object, or a Buffalo object,
//or a String? Does the methods ‘if(TYPE(vsubject)==T_OBJECT){…}’
or
//‘if(rb_obj_is_instance_of(vsubject,“Rat”)){…}’ work for this
purpose?

}

cRanch = rb_define_class(“Ranch”, rb_cObject);

rb_define_method(cRanch, “initialize”, ranch_initialize, -1);

Thank you very much!

Best Regards,
Shiwei

shiwei zhang wrote:

how should I judge/decide
the variable vsubject is a Rat object, or a Buffalo object, or a
String?

If you want to include inheritance:

rb_obj_is_kind_of(obj, some_class)

If you do not, you can use the CLASS_OF macro:

CLASS_OF(obj) == some_class

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs