A question about name reflection

(Barry) #1

Hello All

Sorry if the answer to this question is obvious, I'm new to the language.

I'm considering ruby for a project and I was wondering if it provided some particular functionality.

Say you are writing some extensions to Ruby and you have something like:

     rb_define_method(rb_cMethod, "call", method_call, -1);
     rb_define_method(rb_cMethod, "[]", method_call, -1);

At least 2 different method names in ruby that call the same piece of C code..

static VALUE
method_call(argc, argv, method)
     int argc;
     VALUE *argv;
     VALUE method;
{
     VALUE result = Qnil; /* OK */
     struct METHOD *data;
     int state;
     volatile int safe = -1;

     Data_Get_Struct(method, struct METHOD, data);
     if (data->recv == Qundef) {
     rb_raise(rb_eTypeError, "you cannot call unbound method; bind first");
     }
     PUSH_ITER(rb_block_given_p()?ITER_PRE:ITER_NOT);
     PUSH_TAG(PROT_NONE);
     if (OBJ_TAINTED(method)) {
     safe = ruby_safe_level;
     if (ruby_safe_level < 4) ruby_safe_level = 4;
     }
     if ((state = EXEC_TAG()) == 0) {
     result = rb_call0(data->klass,data->recv,data->id,data- >oid,argc,argv,data->body,0);
     }
     POP_TAG();
     POP_ITER();
     if (safe >= 0) ruby_safe_level = safe;
     if (state) JUMP_TAG(state);
     return result;
}

Now can the C function method_call determine what "name" the ruby caller used when method_call was invoked? "call" or "[]"?

Thanks in advance for any help...

Barry

I believe that a scientist looking at nonscientific problems is just as dumb as the next guy.
--Richard Feynman

(Tim Hunter) #2

Barry wrote:

Now can the C function method_call determine what "name" the ruby caller used when method_call was invoked? "call" or "[]"?

Try rb_frame_last_func(). I use

rb_id2name(rb_frame_last_func())

to get the current method's name as a C string.

(Barry) #3

Thank very much Mr Hunter, perfect answer.

Do you perchance know how I can get the name of the class and module that the method belongs to?

Sorry if these are silly questions, I'm just starting out with this.

On the other hand if you have any really, really hard Prolog questions, I'm your guy....

Thanks in advance

Barry Evans

···

On 22-Aug-05, at 5:31 AM, Timothy Hunter wrote:

Barry wrote:

Now can the C function method_call determine what "name" the ruby caller used when method_call was invoked? "call" or "[]"?

Try rb_frame_last_func(). I use

rb_id2name(rb_frame_last_func())

to get the current method's name as a C string.

If they want peace, nations should avoid the pin-pricks that precede cannon shot
- Napoleon Bonaparte