Add your own C method to an existing Ruby class

I would like to know how to add my own method written in C extension to an existing Ruby class? I just found a function that allows you to create a new Ruby class, but not one of them returns an existing class.

+4
source share
1 answer

Yes, you can. In either case, you are using rb_define_method (or rb_define_singleton_method for rb_define_singleton_method methods). Assuming you have a c function called rb_some_function that expects 1 parameter (in addition to the self parameter), you would do

 rb_define_method(someClass, "some_function", RUBY_METHOD_FUNC(rb_some_function), 1); 

It depends on whether someClass is a class just created (created using rb_define_class_under or rb_define_class ) or an existing class. You can use the rb_const_get method (same as Object const_get ) to get existing classes.

 someClass = rb_const_get(rb_cObject, rb_intern("SomeClass")); 

rb_define_class will also select an existing class for you (similar to re-opening a class in ruby). It will explode in the same way if you try to define a class with a superclass, and the class already exists with another.

+8
source

Source: https://habr.com/ru/post/1493180/


All Articles