How can I call C++ functions from within ruby

You have 3 possibilities :

1) Ruby is able to load libraries. Even if it is a bit tricky, you can decide to write your own loader and bind your C++ library in Ruby. This is done using what is called an extension module. You will find a comprehensive tutorial here: http://www.rubyinside.com/how-to-create-a-ruby-extension-in-c-in-under-5-minutes-100.html

2) You can use a tool that will generate the Ruby wrapper around your C++ library. Look at SWIG for example (http://www.swig.org/). You just have to create a file in a swig-specific syntax and provide it to SWIG. It will then be able to generate the wrapper for many languages, Ruby included.

3) You can choose to use a middleware, such as CORBA/ICE/whatever. It may be a bit overkill if you only want to call some C++ functions, but it will allow you to remote call the functions, or "hide" a grid behind the middleware.


To call C++ code from Ruby, you will likely want to build an extension.

If you are an experienced C++ developer, you may feel comfortable with Rice:

https://github.com/jasonroelofs/rice

It uses C++ metaprogramming techniques to simplify writing extensions.

If you were calling into C, you could also use ffi. Calling C++ code is a little more complicated than calling C code due to name mangling and exceptions.


I believe the questioner is asking how to call C++ from with in Ruby, if so then the for simple C/C++ RubyInline1 is by the far the simplest solution.

Alternatively if you need to call more substatntial C++ code, you can build a ruby extension. Here is a good tutorial


You need to wrap your c++ code in a C interface and then bind those C functions to ruby methods using rb_define_method()

alternatively you can use SWIG, as Aurelien said.