Forum: Ruby Calling class methods from C

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Robert R. (Guest)
on 2009-01-22 21:12
Hello,

I'm trying to call a class method from C. I've tried all combinations of
rb_intern I could think of to make it work, but I've gotten nothing.

Example class

class CallTest
def go
(do something here)
end

end

rb_funcall(?, rb_intern("go"), 0);

What goes in the ? space? I know if I use Qnil there, it will call
global functions, but I'd prefer class methods.

Am I heading in the wrong direction?

Also, I'd prefer not to have to know the class name ahead of time if
possible, but if I have to require that I know what it is, I can try
passing it by name to my application.

I'm using SWIG to generate the binding.
Jason R. (Guest)
on 2009-01-22 21:25
(Received via mailing list)
From the top of my head:

rb_funcall(rb_const_get("CallTest"), rb_intern("go"), 0);

And if you're calling "global" methods, it's better to call it on
Kernel, where the methods are defined anyway:

rb_funcall(rb_mKernel, rb_intern("method_name"), args);

Hope that helps.

Jason
Jason R. (Guest)
on 2009-01-22 21:30
(Received via mailing list)
Bah, saw a small issue right when I hit "Send".

My call line works for a class defined as such:

class CallTest
   def self.go
      (do something here)
   end
end

If you need to call an instance method on an instance of the class
CallTest, you need to of course get a hold of that instance, or make a
new one:

VALUE obj = rb_funcall(rb_const_get("CallTest"), rb_intern("new"), 0);
rb_funcall(obj, rb_intern("go"), 0);

Jason
Robert R. (Guest)
on 2009-01-22 21:36
Jason R. wrote:
> Bah, saw a small issue right when I hit "Send".
>
> My call line works for a class defined as such:
>
> class CallTest
>    def self.go
>       (do something here)
>    end
> end
>
> If you need to call an instance method on an instance of the class
> CallTest, you need to of course get a hold of that instance, or make a
> new one:
>
> VALUE obj = rb_funcall(rb_const_get("CallTest"), rb_intern("new"), 0);
> rb_funcall(obj, rb_intern("go"), 0);
>
> Jason

I tried using rb_const_get but it doesn't appear to call the method.
What should I use for those parameters (VALUE and ID)?
This topic is locked and can not be replied to.