Computer Science Canada

Writing Ruby in C

Author:  wtd [ Thu Sep 29, 2005 12:08 pm ]
Post subject:  Writing Ruby in C

An excruciatingly simple example to demonstrate that it's possible to write Ruby code in C.

First off you'll need the Ruby development header files, a C compiler, and a "make" utility... preferably the GNU toolchain.

The first of those you should get with the standard Ruby distribution. If you're using a packaged version for a Linux distro, you may have to search harder. When in doubt, compile Ruby from source.

Once you've accomplished that, we need to create a C function to wrap. In "function.h":

code:
#ifndef SAY_HELLO_H
#define SAY_HELLO_H

void say_hello();

#endif


And in "function.c":

code:
#include "function.h"
#include <stdio.h>

void say_hello()
{
   printf("Hello\n");
}


Now, in "myfunc.c" we'll write our Ruby extension.

code:
#include "ruby.h"
#include "function.h"

static VALUE wrapped_say_hello(VALUE self)
{
   say_hello();

   return self;
}

void Init_myfunc()
{
   rb_define_method(rb_cObject, "say_hello", wrapped_say_hello, 0);
}


Now, the compilation isn't hard, but it's not exactly easy, either, so I need some way to create a makefile. Ruby comes to the aid.

In file "extconf.rb":

code:
require 'mkmf'

dir_config 'myfunc'

create_makefile 'myfunc'


And then we need only run:

code:
$ ruby extconf.rb && make


Our Ruby extension is now happily sitting there as "myfunc.so".

Starting up IRB we can now:

code:
$ irb --simple-prompt
>> require 'myfunc'
=> true
>> say_hello
Hello
=> nil
>>exit
$


Questions? Smile

Author:  Tony [ Thu Sep 29, 2005 12:19 pm ]
Post subject: 

and on the flip side

Ruby Inline -- writing C in Ruby Laughing

Author:  wtd [ Thu Sep 29, 2005 12:31 pm ]
Post subject: 

I like to think of Ruby's C API as being the Ruby equivalent of assembly.

Author:  md [ Tue May 30, 2006 10:28 am ]
Post subject: 

very nice... Makes me almost want to give it a try Wink


: