Search code examples
rubyruby-c-extension

Add a C native method to a pre-existing Ruby class


I would like to know how to add a native method written in a C extension to a pre-existing Ruby class ? I only found function that allow you to create new Ruby class, but none which returns a pre-existing class.


Solution

  • Yes you can. In either case you use rb_define_method (or rb_define_singleton_method for singleton methods). Assuming you have a c function called rb_some_function that expects 1 parameter (in addition to the self parameter) you'd do

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

    It's up to you whether someClass is a freshly created class (created with rb_define_class_under or rb_define_class) or an existing class. You can use rb_const_get (same as Object's const_get) method to get existing classes.

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

    rb_define_class will also fetch an existing class for you (similar to reopening a class in ruby). It will blow up in a similar way if you try to define a class with a superclass and the class already exists with a different one.