36

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?

Appleshell
  • 7,088
  • 6
  • 47
  • 96

4 Answers4

37

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.

NewbiZ
  • 2,395
  • 2
  • 26
  • 40
15

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.

sunnyrjuneja
  • 6,033
  • 2
  • 32
  • 51
Paul Brannan
  • 1,625
  • 20
  • 20
  • any idea if rice is compatible with windows? – Itzik984 Dec 13 '16 at 09:31
  • 4
    I originally wrote Rice on Windows (tested with mingw and cygwin, and ran into interesting autotools bugs I had to work around). Since I no longer maintain it, I don't know if the most recent versions are well-tested on Windows, but I see no reason why it wouldn't work. I typically interface with C++ these days using IPC (tcp, zeromq, unix socket, etc.). If I needed to call C++ library code directly, I'd probably experiment with Cling. – Paul Brannan Dec 13 '16 at 13:33
  • 1
    Thank you for the answer sir :) – Itzik984 Dec 13 '16 at 13:35
6

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

sunnyrjuneja
  • 6,033
  • 2
  • 32
  • 51
hhafez
  • 38,949
  • 39
  • 113
  • 143
2

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.

horseyguy
  • 29,455
  • 20
  • 103
  • 145