Programming C, C++, Java, PHP, Ruby, Turing, VB
Computer Science Canada 
Programming C, C++, Java, PHP, Ruby, Turing, VB  

Username:   Password: 
 RegisterRegister   
 Writing Ruby in C
Index -> Programming, Ruby -> Ruby Tutorials
View previous topic Printable versionDownload TopicRate TopicSubscribe to this topicPrivate MessagesRefresh page View next topic
Author Message
wtd




PostPosted: 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
Sponsor
Sponsor
Sponsor
sponsor
Tony




PostPosted: Thu Sep 29, 2005 12:19 pm   Post subject: (No subject)

and on the flip side

Ruby Inline -- writing C in Ruby Laughing
wtd




PostPosted: Thu Sep 29, 2005 12:31 pm   Post subject: (No subject)

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




PostPosted: Tue May 30, 2006 10:28 am   Post subject: (No subject)

very nice... Makes me almost want to give it a try Wink
Display posts from previous:   
   Index -> Programming, Ruby -> Ruby Tutorials
View previous topic Tell A FriendPrintable versionDownload TopicRate TopicSubscribe to this topicPrivate MessagesRefresh page View next topic

Page 1 of 1  [ 4 Posts ]
Jump to:   


Style:  
Search: