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

**URL:** <https://www.ruby-forum.com/t/swig-and-ruby-a-nice-way-of-using-c-c-code/138104>\
**Category:** Ruby\
**Created:** [May 20, 2008, 8:40am UTC](https://www.ruby-forum.com/t/swig-and-ruby-a-nice-way-of-using-c-c-code/138104 "2008-05-20T08:40:02Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![kyleh](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/k/a9a28c/32.png) [@kyleh](https://www.ruby-forum.com/u/kyleh)\
**Post date:** [May 20, 2008, 8:40am UTC](https://www.ruby-forum.com/t/swig-and-ruby-a-nice-way-of-using-c-c-code/138104/1 "2008-05-20T08:40:02Z")

</div>

Hi guys,

I was just messing around and discovered Swig [[http://www.swig.org/](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  
[[SWIG and Ruby](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  
out!:  
irb(main):001:0\> require ‘multiply’  
=\> true  
irb(main):002:0\> Multiply.multiply(2,3)  
=\> 6.0

---

<div class="post-metadata">

**Author:** ![kyleh](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/k/a9a28c/32.png) [@kyleh](https://www.ruby-forum.com/u/kyleh)\
**Post date:** [May 20, 2008, 10:30am UTC](https://www.ruby-forum.com/t/swig-and-ruby-a-nice-way-of-using-c-c-code/138104/2 "2008-05-20T10:30:55Z")

</div>

Oops:

The interface file (multiply.i) should actually look like this: [as per  
[SWIG Tutorial](http://www.swig.org/tutorial.html)]

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

Sorry about that
