tags:

views:

286

answers:

4

Hi I am an experienced C/C++ developer but I am a novice in Ruby.

How can I call a C++ function from with in Ruby?

Sorry for the noob question.

+4  A: 

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.

Aurélien Vallée
A: 

I believe the questioner is asking how to call C++ from with in Ruby, if so then the for simple C/C++ RubyInline 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

hhafez
A: 

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.

banister
+1  A: 

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:

http://github.com/jameskilton/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.

Paul Brannan