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

S

shiwei zhang

[Note: parts of this message were removed to make it a legal post.]

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
 
J

Joel VanderWerf

shiwei said:
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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,581
Members
45,057
Latest member
KetoBeezACVGummies

Latest Threads

Top