
-----------------------------------
wtd
Thu Sep 29, 2005 12:08 pm

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":

#ifndef SAY_HELLO_H
#define SAY_HELLO_H

void say_hello();

#endif

And in "function.c":

#include "function.h"
#include 

void say_hello()
{
   printf("Hello\n");
}


Now, in "myfunc.c" we'll write our Ruby extension.

#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":  

require 'mkmf'

dir_config 'myfunc'

create_makefile 'myfunc'

And then we need only run:

$ ruby extconf.rb && make

Our Ruby extension is now happily sitting there as "myfunc.so".

Starting up IRB we can now:

$ irb --simple-prompt
>> require 'myfunc'
=> true
>> say_hello
Hello
=> nil
>>exit
$

Questions?  :)

-----------------------------------
Tony
Thu Sep 29, 2005 12:19 pm


-----------------------------------
and on the flip side

[url=http://rubyforge.org/projects/rubyinline/]Ruby Inline -- writing C in Ruby :lol:

-----------------------------------
wtd
Thu Sep 29, 2005 12:31 pm


-----------------------------------
I like to think of Ruby's C API as being the Ruby equivalent of assembly.

-----------------------------------
md
Tue May 30, 2006 10:28 am


-----------------------------------
very nice... Makes me almost want to give it a try ;-)
