How can I call C++ functions from within ruby

24,120

Solution 1

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.

Solution 2

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.

Solution 3

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

Solution 4

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.

Share:
24,120
Admin
Author by

Admin

Updated on January 09, 2020

Comments

  • Admin
    Admin over 4 years

    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?

  • Magpie
    Magpie almost 10 years
    The question is about c++ so 1. is not relevant.
  • Itzik984
    Itzik984 over 7 years
    any idea if rice is compatible with windows?
  • Paul Brannan
    Paul Brannan over 7 years
    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.
  • Itzik984
    Itzik984 over 7 years
    Thank you for the answer sir :)