Rice
3.0.0
|
Rice is a C++ interface to Ruby's C API. It provides a type-safe and exception-safe interface in order to make embedding Ruby and writing Ruby extensions with C++ easier. It is similar to Boost.Python or pybind11 in many ways, but also attempts to provide an object-oriented interface to all of the Ruby C API.
What Rice gives you:
This documentation and branch are for the 3.x line of Rice. For the header-only version of Rice use the master
branch and any version from 4.x onward.
The documentation for the 4.x line is found at http://ruby-rice.github.io/4.x.
The source is hosted on GitHub: http://github.com/ruby-rice/rice
Bug tracking: http://github.com/ruby-rice/rice/issues
API documentation: http://ruby-rice.github.io/
Building it locally from a clone of the repository is as follows:
Rice is known to work on *nix, OSX, and Windows.
Rice requires a C++ compiler with support for C++14 or later.
Writing an extension with Rice is very similar to writing an extension with the C API.
The first step is to create an extconf.rb file:
Note that we use mkmf-rice
instead of mkmf
. This will ensure that the extension will be linked with standard C++ library along with the Rice library, and allow access to the Rice header files.
Next we create our extension and save it to test.cpp:
Note the extern "C" line above. This tells the compiler that the function Init_test
should have C linkage and calling convention. This turns off name mangling so that the Ruby interpreter will be able to find the function (remember that Ruby is written in C, not C++).
So far we haven't put anything into the extension, so it isn't particularly useful. The next step is to define a class so we can add methods to it.
Defining a class in Rice is a single call:
This will create a class called Test
that inherits from Object
. If we wanted to inherit from a different class, we do so with the second parameter:
Note the prefix rb_c on the name of the class. This is a convention that the Ruby interpreter and many extensions tend to use. It signifies that this is a class and not some other type of object. Some other naming conventions that are commonly used:
Also note that we don't include "ruby.h" directly. Rice has a wrapper for ruby.h that handles some compatibility issues across platforms and Ruby versions. Always include Rice headers before including anything that might include "ruby.h".
Now let's add a method to our class:
Here we add a method Test#hello
that returns the string "Hello, World". The method takes self as an implicit parameter, but isn't used, so we comment it out to prevent a compiler warning.
We could also add an #initialize
method to our class:
The initialize
method sets an instance variable @foo
to the value 42. The number is automatically converted to a Fixnum
before doing the assignment.
Note that we're chaining calls on the Class
object. Most member functions in Module
and Class
return a reference to self
, so we can chain as many calls as we want to define as many methods as we want.
It's useful to be able to define Ruby classes in a C++ style rather than using the Ruby API directly, but the real power Rice is in wrapping already-defined C++ types.
Let's assume we have the following C++ class that we want to wrap:
This is a C++ version of the Ruby class we just created in the previous section. To wrap it:
This example is similar to the one before, but we use Data_Type<>
instead of Class
and the template version of define_class() instead of the non-template version. This creates a binding in the Rice library between the Ruby class Test
and the C++ class Test such that Rice passes member function pointers to define_method()
.
It is possible to write the conversion functions ourself (as we'll see below), but Rice does all the dirty work for us.
Let's look again at our example class:
When we wrote our class, we never wrote a single line of code to convert the std::string
returned by hello()
into a Ruby type. Neverthless, the conversion works, and when we write:
We get the expected result.
Rice has two template conversion functions to convert between C++ and Ruby types:
Rice includes default specializations for many of the builtin types. To define your own conversion, write a template specialization:
The implementation of these functions would, of course, depend on the implementation of Foo
.
Take another look at the wrapper we wrote for the Test
class:
When we called define_class<Test>
, it created a Class for us and automatically registered the new Class with the type system, so that the calls:
works as expected.
The Data_Object
class is a wrapper for the Data_Wrap_Struct
and the Data_Get_Struct
macros in C extensions. It can be used to wrap or unwrap any class that has been assigned to a Data_Type
. It inherits from Object
, so any member functions we can call on an Object
we can also call on a Data_Object
:
The Data_Object
class can be used to wrap a newly-created object:
or to unwrap an already-created object:
A Data_Object
functions like a smart pointer:
Like a VALUE
or an Object
, data stored in a Data_Object
will be marked by the garbage collector as long as the Data_Object
is on the stack.
Suppose we added a member function to our example class that throws an exception:
If we were to wrap this function:
and call it from inside Ruby:
we would get an exception. Rice will automatically convert any C++ exception it catches into a Ruby exception. But what if we wanted to use a custom error message when we convert the exception, or what if we wanted to convert to a different type of exception? We can write an exception handler like so:
The handle_my_exception
function need only rethrow the exception as a Rice::Exception
:
And what if we want to call Ruby code from C++? These exceptions are also converted:
Internally whenever Rice catches a C++ or a Ruby exception, it converts it to an Exception
object. This object will later be re-raised as a Ruby exception when control is returned to the Ruby VM.
Rice uses a similar class called Jump_Tag
to handle symbols thrown by Ruby's throw
/catch
or other non-local jumps from inside the Ruby VM.
You've seen this example:
Rice mimics the Ruby class hierarchy as closely as it can. In fact, the above code also works for Classes:
Rice provides builtin wrappers for many builtin Ruby types, including:
The Array
and Hash
types can even be iterated over the same way one would iterate over an STL container:
STL algorithms should also work as expected on Array
and Hash
containers.
Inheritance is a tricky problem to solve in extensions. This is because wrapper functions for base classes typically don't know how to accept pointers to derived classes. It is possible to write this logic, but the code is nontrivial.
Rice also provides a solution to this problem:
The second template parameter to define_class indicates that Derived
inherits from Base
.
Rice does not support multiple inheritance.
If you try to create a member function pointer to an overloaded function, you will get an error. So how do we wrap classes that have overloaded functions?
Consider a class that uses this idiom for accessors:
We can wrap this class by using typedef
s:
Rice provides default conversions for many built-in types. Sometimes, however, the default conversion is not what is expected. For example, consider a function:
Is x
a pointer to a single character or a pointer to the first character of a null-terminated string or a pointer to the first character of an array of char?
Because the second case is the most common use case (a pointer to the first character of a C string), Rice provides a default conversion that treats a char *
as a C string. But suppose the above function actually expects to receive a pointer to a single char instead?
If we write this:
It will likely have the wrong behavior.
To avoid this problem, it is necessary to write a wrapper function where the extension can be more explicit about how to handle the parameters:
Note that the out parameter is returned from wrap_foo
, as Ruby does not have pass-by-variable-reference (it uses pass-by-object-reference).
Going back to our initial C++ class example, lets say that hello()
now takes more arguments, one of which has a default value:
As default parameter information is not available through templates, it is necessary to define this in Rice explicitly using Rice::Arg
:
The syntax here is Arg(nameOfParameter)[ = defaultValue]
. The name of the parameter is not important here (it is for readability), but the value set via operator=
must match the type of the parameter. As such it may be necessary to explicitly cast the default value.
These Rice::Arg
objects must be in the correct order and must be surrounded with parentheses if more than one exists.
Now, Ruby will now know about the default arguments, and this wrapper can be used as expected:
This also works with Constructors:
Polymorphism creates yet another wrinkle in building exceptions around C++ code, because now we have to deal with cross-language polymorphism, where C++ can call into a Ruby subclass, and a Ruby subclass can super
back into C++ land. super
calls already work through define_class, but making code travel from C++ into Ruby via polymorphism is tricker. Rice provides the Rice::Director
class and the define_director
method to enable this code path.
Like SWIG_Director
, Rice::Director
is a class that is used to build a proxy class to properly send execution up or down the object hierarchy for that class. Take the following class:
Due to the abstract nature of this class, we cannot directly wrap it in Rice, as any C++ compiler will complain about trying to instantiate a virtual class. Even without the pure virtual function, any call to VirtualBase::doWork
will stop at the C++ level and execution will not pass down into any Ruby subclasses.
To properly wrap both of these methods, use a Rice::Director
subclass as a proxy and use this new proxy class as the type to wrap with define_class
:
There is a lot going on here, so we'll go through each part.
First, the class needs to subclass both the virtual class in question and Rice::Director
.
For Rice::Director
to work its magic, every instance of this class needs to have a handle to its Ruby instance. The constructor must take a Rice::Object
as the first argument and pass it up into Rice::Director
. The code here is the minimum required for a Rice::Director
proxy.
Here the proxy class implements the virtual methods and provides implementations that delegate execution in the correct direction. The actual method calls into Ruby, providing all necessary type conversions to and from C++ types. The other method is how Ruby calls back into C++ and is the method that must be exposed with define_method
. The default_
prefix is a naming convention to help keep straight which methods perform which function. If Ruby should never call into C++, then the default_
implementation should call raisePureVirtual()
:
The method raisePureVirtual()
exists to allow wrapping a pure virtual method into Ruby (and ensuring compliation is possible) but making sure any users of this extension are informed quickly that there's nothing callable in the C++ side of the library.
Once the proxy class is built, it's time to wrap it into Ruby:
The wrapping is the same as is described earlier in this document. Expose the class VirtualBase
, and register VirtualBaseProxy
as a director proxy of VirtualBase
with Rice::Data_Type::define_director
, then define_method
s pointing to the proxy methods as necessary.
You must use the Rice::Director
proxy class in the Constructor line, this allows proper object construction / destruction of the types in question.
There are times when a library exposes classes that, while unrelated, are built to be interchangeable across the library. One example of this is found in the Open Source 3d rendering engine OGRE: Ogre::Degree and Ogre::Radian. When a given method takes a Radian, you're free to pass in a Degree, and vice versa.
Rice cannot automatically figure out if this kind of functionality is possible in a given library but it does provide an API for defining these relationships: Rice::define_implicit_cast<From, To>()
.
Using Rice::define_implicit_cast
has the following requirements:
To see a full example of this feature, please check out test/test_Data_Type.cpp.
There are a number of common problems when writing C or C++ extensions for Ruby:
Rice addresses these issues in many ways:
There are a number projects which server similar functions to Rice. Two such popular projects are SWIG and Boost.Python. Rice has some distinct features which set it apart from both of these projects.
Rice is not trying to replace SWIG. Rice is not a generic wrapper interface generator. Rice is a C++ library for interfacing with the Ruby C API. This provides a very natural way for C++ programmers to wrap their C++ code, without having to learn a new domain-specific language. However, there is no reason why SWIG and Rice could not work together; a SWIG module could be written to generate Rice code. Such a module would combine the portability of SWIG with the maintainability of Rice (I have written extensions using both, and I have found Rice extensions to be more maintainable when the interface is constantly changing. Your mileage may vary).
Rice is also not trying to simply be a Ruby version of Boost.Python. Rice does use some of the same template tricks that Boost.Python uses, however there are some important distinctions. First of all, Boost.Python attempts to create a declarative DSL in C++ using templates. Rice is a wrapper around the Ruby C API and attempts to make its interface look like an OO version of the API; this means that class declarations look procedural rather than declarative. Secondly, the Ruby object model is different from the python object model. This is reflected in the interface to Rice; it mimics the Ruby object model at the C++ level. Thirdly, Rice uses Ruby as a code generator; I find this to be much more readable than using the Boost preprocessor library.
Rice originated as Excruby, a project to interface with C++-based trading software at Automated Trading Desk in Mount Pleasant, South Carolina. The Ruby bindings for Swig were at the time less mature than they are today, and did not suit the needs of the project.
Excruby was written not as a wrapper for the Ruby API, but rather as a set of helper functions and classes for interfacing with the Ruby interpreter in an exception-safe manner. Over the course of five years, the project grew into wrappers for pieces of the API, but the original helper functions remained as part of the public interface.
This created confusion for the users of the library, because there were multiple ways of accomplishing most tasks – directly through the C API, through a low-level wrapper around the C API, and through a high-level abstraction of the lower-level interfaces.
Rice was then born in an attempt to clean up the interface. Rice keeps the lower-level wrappers, but as an implementation detail; the public interface is truly a high-level abstraction around the Ruby C API.