Last Updated: February 25, 2016
·
1.895K
· tonyfabeen

Extending Ruby with C - a taste of

There is not complications extending Ruby. Of course, you at least should have a basic C knowledge.

Let's create a simple example :

Create a directory to our Ruby Extension:

mkdir <your_path>/coderwall

Create a C file named coderwall.c, inside that include ruby.h header.
c include <ruby.h>

Everything is a VALUE in Ruby, so to create a module, let's create a mCoderwall representing that:

VALUE mCoderwall;

And a VALUE to represent a class behind this module:

VALUE cTalker;

Our Talker class should do something. Let's create a function that returns a Ruby String.

static VALUE say_yeah(VALUE self){
  const char *sentence= "YEAH YEAH!";
  return rb_str_new2(sentence);
}

In the function say_yeah VALUE self represents our self object.
sentence is string tp be returned
And the function rb_str_new2 converts a *char to a Ruby String

To translate our extension to Ruby World, we create a function Init_coderwall It must always starts with Init_.

void Init_coderwall(){
  mCoderwall = rb_define_module("Coderwall");
  cTalker = rb_define_class_under(mCoderwall, "Talker", rb_cObject);
  rb_define_singleton_method(cTalker, "say_yeah", say_yeah, 0);
}

The function rb_define_module defines a module at the top level Hierarchy. Same as :

module Coderwall

end

The function rb_define_class_under defines a class under a module or another class. It will create:

module Coderwall
  class Talker

  end
end

The function rb_define_singleton_method creates a singleton method under some class or module. In this case, under Talker class.

To run our code we should create a file called extconf.rb and put it the content bellow inside.

require 'mkmf'
create_makefile('coderwall')

Execute the script. It will create a Makefile to build the extension.

$ ruby extconf.rb

Compile and Install the Extension

$ make && make install

To see the code working you can require our new extension and execute it :

$irb(main):001:0> require 'coderwall'
true

$irb(main):002:0> Coderwall::Talker.say_yeah
"YEAH YEAH!"

YEAH YEAH !!

1 Response
Add your response