Swig and Ruby - a nice way of using C/C++ code

Hi guys,

I was just messing around and discovered Swig [http://www.swig.org/]
works fine with ruby! It allows you to use C/C++ code from Ruby and MANY
other languages.

I know we already have RubyInline, of course, which works fantastically.

Heres how you use it… just a quick paraphrase of docs
[http://www.swig.org/Doc1.3/Ruby.html] (on Linux & friends… for
Windows, consult the documentation)

Make a function or two in C/C++ (multiply.c):
float multiply(float t1,float t2) {
return t1*t2;

Now you need to make an interface file (multiply.i):
extern float multiply(float t1, float t2);

You can also include header files in the interface file, consult docs -
otherwise just list the functions.

Now lets pipe a few commands into our shells:
swig -ruby multiply.i #For C - will generate multiply_wrap.c - use -c++
if you using C++ code
gcc -c multiply.c multiply.c -I/usr/lib/ruby/1.8/i486-linux #Change to
directory with ruby.h/etc.
gcc -shared multiply.o multiply_wrap.o -o multiply.so

Now open up IRB in the directory of our new multiply library and try it
irb(main):001:0> require ‘multiply’
=> true
irb(main):002:0> Multiply.multiply(2,3)
=> 6.0


The interface file (multiply.i) should actually look like this: [as per

%module multiply
extern float multiply(float t1, float t2);
extern float multiply(float t1, float t2);

Sorry about that

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs