<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Forty-Two &#187; rice</title>
	<atom:link href="http://jameskilton.com/category/programming/rice/feed/" rel="self" type="application/rss+xml" />
	<link>http://jameskilton.com</link>
	<description>On gaming, programming, everything!</description>
	<lastBuildDate>Fri, 02 Dec 2011 22:04:24 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.2.1</generator>
		<item>
		<title>How Rice Works</title>
		<link>http://jameskilton.com/2010/02/23/how-rice-works/</link>
		<comments>http://jameskilton.com/2010/02/23/how-rice-works/#comments</comments>
		<pubDate>Tue, 23 Feb 2010 14:13:25 +0000</pubDate>
		<dc:creator>Jason</dc:creator>
				<category><![CDATA[everything!]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[rice]]></category>
		<category><![CDATA[ruby]]></category>

		<guid isPermaLink="false">http://jameskilton.com/?p=227</guid>
		<description><![CDATA[Rice is one impressive piece of software. I highly doubt I could have written this from scratch (and for that I give Paul Brannan huge accolades for his work) but after working with and on this library for at least a year I probably could. Now that lead maintainership has been passed on to me, [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://rice.rubyforge.org">Rice</a> is one impressive piece of software. I highly doubt I could have written this from scratch (and for that I give Paul Brannan huge accolades for his work) but after working with and on this library for at least a year I probably could. Now that lead maintainership has been passed on to me, I&#8217;d like to take some time to explain exactly how Rice works, how one can dive in and help develop this library, and what my plans are for the near future as I work to make Rice and the <a href="http://rbplusplus.rubyforge.org">rb++ suite</a>; a full and proper replacement for <a href="http://www.swig.org">SWIG</a> when wrapping C++ libraries into Ruby (if you&#8217;re wrapping a pure C library, I highly recommend <a href="http://github.com/ffi/ffi">Ruby-FFI</a>, though Rice will work).</p>
<p>So with that, I&#8217;m putting together this post to help clarify exactly how the various parts of Rice work together, how the entire process flows and more importantly helping anyone who&#8217;s wanting to learn and work on Rice with a solid starting point (or at least officially crooked). After reading this, anyone should be able to understand the various classes in Rice, and have an idea on where certain functionality lives when looking to add features, or address any bugs. So with that, we&#8217;ll start at the top.</p>
<p><span id="more-227"></span></p>
<h3>What is Rice?</h3>
<p>Rice is a wholly remarkable piece of software that takes complicated C++ classes, methods, types, etc and exposes them into Ruby using as simple an API as can be made. In short, you can take a C++ class such as:</p>

<div class="wp_syntax"><div class="code"><pre class="cpp" style="font-family:monospace;"><span style="color: #0000ff;">class</span> Generator <span style="color: #008000;">&#123;</span>
  <span style="color: #0000ff;">public</span><span style="color: #008080;">:</span>
    Generator<span style="color: #008000;">&#40;</span><span style="color: #0000ff;">int</span> seed<span style="color: #008000;">&#41;</span> <span style="color: #008080;">:</span> mSeed<span style="color: #008000;">&#40;</span>seed<span style="color: #008000;">&#41;</span> <span style="color: #008000;">&#123;</span> <span style="color: #008000;">&#125;</span>
    ~Generator<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span> <span style="color: #008000;">&#123;</span> <span style="color: #008000;">&#125;</span>
&nbsp;
    <span style="color: #0000ff;">int</span> getRandomInt<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span> <span style="color: #008000;">&#123;</span> <span style="color: #0000ff;">return</span> <span style="color: #0000dd;">4</span><span style="color: #008080;">;</span> <span style="color: #008000;">&#125;</span> <span style="color: #666666;">// chosen by dice roll, guaranteed to be random</span>
&nbsp;
    <span style="color: #0000ff;">void</span> setSeed<span style="color: #008000;">&#40;</span><span style="color: #0000ff;">int</span> seed<span style="color: #008000;">&#41;</span> <span style="color: #008000;">&#123;</span> mSeed <span style="color: #000080;">=</span> seed<span style="color: #008080;">;</span> <span style="color: #008000;">&#125;</span>
&nbsp;
  <span style="color: #0000ff;">private</span><span style="color: #008080;">:</span>
    <span style="color: #0000ff;">int</span> mSeed<span style="color: #008080;">;</span>
<span style="color: #008000;">&#125;</span><span style="color: #008080;">;</span></pre></div></div>

<p>and use in in Ruby seemlessly:</p>

<div class="wp_syntax"><div class="code"><pre class="ruby" style="font-family:monospace;">g = <span style="color:#CC00FF; font-weight:bold;">Generator</span>.<span style="color:#9900CC;">new</span><span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#006666;">5</span><span style="color:#006600; font-weight:bold;">&#41;</span>
g.<span style="color:#9900CC;">random_int</span>          <span style="color:#008000; font-style:italic;"># =&gt; 4</span>
g.<span style="color:#9900CC;">seed</span> = <span style="color:#006666;">10</span></pre></div></div>

<p>through a very simple Rice wrapper Ruby extension:</p>

<div class="wp_syntax"><div class="code"><pre class="c" style="font-family:monospace;"><span style="color: #993333;">void</span> Init_generator<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
   define_class<span style="color: #339933;">&lt;</span>Generator<span style="color: #339933;">&gt;</span><span style="color: #009900;">&#40;</span><span style="color: #ff0000;">&quot;Generator&quot;</span><span style="color: #009900;">&#41;</span>.
      <span style="color: #202020;">define_constructor</span><span style="color: #009900;">&#40;</span>Constructor<span style="color: #339933;">&lt;</span>Generator<span style="color: #339933;">,</span> int<span style="color: #339933;">&gt;</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span>.
      <span style="color: #202020;">define_method</span><span style="color: #009900;">&#40;</span><span style="color: #ff0000;">&quot;random_int&quot;</span><span style="color: #339933;">,</span> <span style="color: #339933;">&amp;</span>Generator<span style="color: #339933;">::</span><span style="color: #202020;">getRandomInt</span><span style="color: #009900;">&#41;</span>.
      <span style="color: #202020;">define_method</span><span style="color: #009900;">&#40;</span><span style="color: #ff0000;">&quot;seed=&quot;</span><span style="color: #339933;">,</span> <span style="color: #339933;">&amp;</span>Generator<span style="color: #339933;">::</span><span style="color: #202020;">setSeed</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>Were this class to be wrapped using Ruby&#8217;s C-API, every method on Generator, and even the constructor would have to be wrapped in a C method with calls into Ruby&#8217;s API (particularly Data_Make_Struct and Data_Get_Struct), very tedious and time consuming work, and at times quite error prone. So how does Rice make this tedious process as simple as four lines of code? C++ templates, and lots of them. We&#8217;ll go through each line here and dive into Rice itself to see what&#8217;s happening, but first, a quick word on Rice&#8217;s file naming convention.</p>
<h4>ipp, hpp, cpp, _defn &#8230; what??</h4>
<p>Because Rice is so template driven, most of the code cannot be pre compiled. That which can gets put into cpp files and ends up in librice.a, otherwise the core of Rice is template code generation which means only the code needed for the given extension is generated and compiled when building the extension itself. Given this, Rice still tries to strongly adhere to the separation of definition and implementation code. The definitions of classes are normally placed in [class_name]_defn.hpp, with the implementation placed in [class_name].ipp (to keep it separate from compilable code which gets placed in .cpp files). These two files are then combined in [class_name].hpp which is meant to be used in Rice extensions when including various pieces of functionality. When working inside of Rice and you need class definitions, you&#8217;ll want to use #include &#8220;[class_name]_defn.hpp&#8221; in most cases or risk running into circular dependencies and &#8220;already defined&#8221; compiler errors. Otherwise, when writing an extension using Rice, you&#8217;ll #include &#8220;[class_name].hpp&#8221; to ensure that all functionality is available for the extension.</p>
<p>As for the .mustache files, a lot of Rice&#8217;s template code is very repetitive and so instead of using complicated macros like Boost.Python does, Rice simply uses Ruby to generate the C++ code. Rice currently uses the <a href="http://defunkt.github.com/mustache/">Mustache</a> library for this and the code for this process can be seen in rice/code_gen.</p>
<h4>Defining a class: define_class</h4>
<p>To expose a C++ class into Ruby you first need to define the class, give it a name, and tell Rice which C++ type this class is (as a side note, you can create a Ruby class not hooked to a C++ type, just don&#8217;t give define_class a type). The prototypes of define_class are found in Data_Type_defn.hpp. The one we are particularly interested in is:</p>

<div class="wp_syntax"><div class="code"><pre class="cpp" style="font-family:monospace;"><span style="color: #666666;">//! Define a new data class in the default namespace.</span>
<span style="color: #ff0000; font-style: italic;">/*! The class will have a base class of Object.
 *  \param T the C++ type of the wrapped class.
 *  \return the new class.
 */</span>
<span style="color: #0000ff;">template</span><span style="color: #000080;">&lt;</span><span style="color: #0000ff;">typename</span> T<span style="color: #000080;">&gt;</span>
Rice<span style="color: #008080;">::</span><span style="color: #007788;">Data_Type</span><span style="color: #000080;">&lt;</span>T<span style="color: #000080;">&gt;</span> define_class<span style="color: #008000;">&#40;</span>
    <span style="color: #0000ff;">char</span> <span style="color: #0000ff;">const</span> <span style="color: #000040;">*</span> name<span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span></pre></div></div>

<p>Following the code into Data_Type.ipp, we can see the implementation of this method:</p>

<div class="wp_syntax"><div class="code"><pre class="cpp" style="font-family:monospace;"><span style="color: #0000ff;">template</span><span style="color: #000080;">&lt;</span><span style="color: #0000ff;">typename</span> T<span style="color: #000080;">&gt;</span>
<span style="color: #0000ff;">inline</span> Rice<span style="color: #008080;">::</span><span style="color: #007788;">Data_Type</span><span style="color: #000080;">&lt;</span>T<span style="color: #000080;">&gt;</span> Rice<span style="color: #008080;">::</span>
<span style="color: #007788;">define_class</span><span style="color: #008000;">&#40;</span>
    <span style="color: #0000ff;">char</span> <span style="color: #0000ff;">const</span> <span style="color: #000040;">*</span> name<span style="color: #008000;">&#41;</span>
<span style="color: #008000;">&#123;</span>
  Class c<span style="color: #008000;">&#40;</span>define_class<span style="color: #008000;">&#40;</span>name, rb_cObject<span style="color: #008000;">&#41;</span><span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
  c.<span style="color: #007788;">undef_creation_funcs</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
  <span style="color: #0000ff;">return</span> Data_Type<span style="color: #000080;">&lt;</span>T<span style="color: #000080;">&gt;</span><span style="color: #008080;">::</span><span style="color: #0000ff;">template</span> bind<span style="color: #000080;">&lt;</span><span style="color: #0000ff;">void</span><span style="color: #000080;">&gt;</span><span style="color: #008000;">&#40;</span>c<span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
<span style="color: #008000;">&#125;</span></pre></div></div>

<p>This method starts out creating a new Rice::Class with the given name, making it a subclass of Object (aka a top-level Class, emulating what Ruby itself does). A quick jump into Class.cpp shows us that define_class(char*, VALUE) simply forwards off to the Ruby API call rb_define_class, then takes the resulting VALUE and wraps it into a Rice::Class. </p>
<p>Rice then undefines #alloc and #initialize to prepare the class for Rice&#8217;s own type management (to be discussed later). The third line of this method is what actually binds this new class to the C++ type, binding it as a top-level class (Data_Type::bind is templated to the superclass type, so void in this case).</p>
<h4>Data_Type binding</h4>
<p>Probably the most confusing, and at the same time most important, aspect of Rice is how it manages C++ types and their link into the Ruby world. Every C++ class that&#8217;s to be wrapped into Ruby must be bound to a Ruby class which is done in the static method Data_Type::bind (implemented in Data_Type.ipp). This logic forms the core of how Rice does automatic conversions from C++ types to Ruby types and vis-versa. </p>
<p>To start, every Data_Type&lt;T&gt; has a static pointer to a Ruby class (Data_Type&lt;T&gt;::klass_). After checking that this C++ class isn&#8217;t already bound to another Ruby class, bind() registers the Ruby class with the Ruby GC and sets up a Caster between this C++ type and the Ruby class (to be discussed later). </p>
<p>We&#8217;ve now got our C++ class Generator properly bound to the Ruby class Generator and can continue.</p>
<h4>Adding methods to a class: define_method</h4>
<p>We&#8217;re now at the point where we can start wrapping the methods on our Generator class. We&#8217;ll follow the code execution of wrapping the method Generator::getRandomInt(), starting with Module::define_method found in Module_impl.hpp.</p>
<p><b>Quick side note:</b> Rice&#8217;s C++ API attempts to mimic Ruby&#8217;s top level Object structure, so the interplay between Data_Type, Module and Class can get confusing. Suffice it to say, class-based objects in Rice are all Rice::Module-s at the top, which then itself is a Rice::Object.</p>
<p>The specific define_method we&#8217;re interested in here is as follows:</p>

<div class="wp_syntax"><div class="code"><pre class="cpp" style="font-family:monospace;">  <span style="color: #666666;">//! Define an instance method.</span>
  <span style="color: #ff0000; font-style: italic;">/*! The method's implementation can be any function or member
   *  function.  A wrapper will be generated which will use from_ruby&lt;&gt;
   *  to convert the arguments from ruby types to C++ types before
   *  calling the function.  The return value will be converted back to
   *  ruby by using to_ruby().
   *  \param name the name of the method
   *  \param func the implementation of the function, either a function
   *  pointer or a member function pointer.
   *  \param arguments the list of arguments of this function, used for
   *  defining default parameters (optional)
   *  \return *this
   */</span>
  <span style="color: #0000ff;">template</span><span style="color: #000080;">&lt;</span><span style="color: #0000ff;">typename</span> Func_T<span style="color: #000080;">&gt;</span>
  Derived_T <span style="color: #000040;">&amp;</span> define_method<span style="color: #008000;">&#40;</span>
      Identifier name,
      Func_T func,
      Arguments<span style="color: #000040;">*</span> arguments <span style="color: #000080;">=</span> <span style="color: #0000dd;">0</span><span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span></pre></div></div>

<p>The Rice::Arguments object has to do with the implementation of default argument definitions and I&#8217;ll get to that later.</p>
<p>This method is the beginning of where the true template craziness (genius? probably) happens. As a warning, if you are not comfortable with templates, the following is either going to confuse you, or it will open your eyes to a whole new level of possibilities in C++.</p>
<p>Rice works directly with Function Pointers and template definitions tailored to react to specific function pointer definitions to generate the appropriate code for properly wrapping C++ methods into Ruby. As a refresher, a C++ function pointer looks like this:</p>

<div class="wp_syntax"><div class="code"><pre class="cpp" style="font-family:monospace;">ReturnType <span style="color: #008000;">&#40;</span>ClassName<span style="color: #008080;">::</span><span style="color: #000040;">*</span>methodName<span style="color: #008000;">&#41;</span><span style="color: #008000;">&#40;</span>ArgT1, ArgT2, ...<span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span></pre></div></div>

<p>so if we were to print out the function pointer of Generator::getRandomInt we would see:</p>

<div class="wp_syntax"><div class="code"><pre class="cpp" style="font-family:monospace;"><span style="color: #0000ff;">int</span> <span style="color: #008000;">&#40;</span>Generator<span style="color: #008080;">::</span><span style="color: #000040;">*</span>getRandomInt<span style="color: #008000;">&#41;</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span></pre></div></div>

<p>This is what Func_T ends up being, a function pointer type. It can be a method with any return type, and any number and type of arguments, all handled by this one method. Looking at the implementation of this in Module_impl.ipp, we can see that execution is simply forwarded off to detail::define_method_and_auto_wrap given the Module/Class/Data_Type (*this), the name, the function pointer, any defined exception handler (this->handler) and the arguments object.</p>
<p>From this point, Rice needs to make a very important distinction on the method being wrapped: is it a class method, or a static method? The method Rice::detail::define_method_and_auto_wrap, defined in detail/define_method_and_auto_wrap.{hpp,ipp} uses Wrapped_Function classes, via wrap_function (detail/wrap_function.{hpp,ipp}) to make this distinction and to set up the final method object before finally jumping into Ruby&#8217;s C-API for finally exposing this method.</p>
<h4>Auto_{,Member}_Function_Wrapper</h4>
<p>Opening up detail/wrap_function.ipp you&#8217;ll see a very long file full of very repetitive method definitions. The key here is this method uses templates to match the passed in function pointer to one of Auto_Function_Wrapper (static functions) or Auto_Member_Function_Wrapper (a class instance method). Due to how Auto_{,Member}_Function_Wrapper works, wrap_function also has to have template specifications for functions with a return type and functions with void, as well as specifications to handle const and non-const function pointers.</p>
<p>To continue from here we need to understand how Rice actually hooks into Ruby. Glancing in detail/Auto_Function_Wrapper.hpp  we&#8217;ll find template-overload classes similar to what&#8217;s in wrap_function. These classes are the core that handle argument and return type management as well as taking execution from Ruby and passing it into the related C++ function or method. What we&#8217;re going to focus on here is the ::call static method, though we&#8217;ll get to the details of this method&#8217;s implementations later. </p>
<p>Ruby&#8217;s API will only take C-style functions with the signature VALUE(*)(&#8230;). The Auto_&#8230;_Wrapper classes are the glue that gives us a function with this signature:</p>

<div class="wp_syntax"><div class="code"><pre class="cpp" style="font-family:monospace;"><span style="color: #0000ff;">static</span> VALUE Auto_Function_Wrapper<span style="color: #008080;">::</span><span style="color: #007788;">call</span><span style="color: #008000;">&#40;</span><span style="color: #0000ff;">int</span> argc, VALUE <span style="color: #000040;">*</span>argv, VALUE self<span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span></pre></div></div>

<p>If you&#8217;re familiar with Ruby&#8217;s C-API, then this signature should look familiar, it&#8217;s the -1 arity signature used when you want to support a variable number of arguments (in Rice&#8217;s case, default arguments). So how does a static function on a templated class work with an instance of this class to call the correct C++ method or function? It&#8217;s time to dive into detail/method_data.cpp, which defines define_method_with_data() as seen in the second part of define_method_and_auto_wrap() (Rice::protect is a wrapper around rb_protect to catch any exceptions and handle them gracefully).</p>
<h4>detail/method_data.cpp</h4>
<p>I&#8217;ll start this section with the comment block describing define_method_with_data():</p>

<div class="wp_syntax"><div class="code"><pre class="cpp" style="font-family:monospace;"><span style="color: #666666;">// Define a method and attach data to it.</span>
<span style="color: #666666;">// The method looks to ruby like a normal aliased CFUNC, with a modified</span>
<span style="color: #666666;">// origin class.</span>
<span style="color: #666666;">//</span>
<span style="color: #666666;">// How this works:</span>
<span style="color: #666666;">//</span>
<span style="color: #666666;">// To store method data and have it registered with the GC, we need a</span>
<span style="color: #666666;">// &quot;slot&quot; to put it in.  This &quot;slot&quot; must be recognized and marked by</span>
<span style="color: #666666;">// the garbage collector.  There happens to be such a place we can put</span>
<span style="color: #666666;">// data, and it has to do with aliased methods.  When Ruby creates an</span>
<span style="color: #666666;">// alias for a method, it stores a reference to the original class in</span>
<span style="color: #666666;">// the method entry.  The form of the method entry differs from ruby</span>
<span style="color: #666666;">// version to ruby version, but the concept is the same across all of</span>
<span style="color: #666666;">// them.</span>
<span style="color: #666666;">// </span>
<span style="color: #666666;">// In Rice, we make use of this by defining a method on a dummy class,</span>
<span style="color: #666666;">// then attaching that method to our real class.  The method is a real</span>
<span style="color: #666666;">// method in our class, but its origin class is our dummy class.</span>
<span style="color: #666666;">// </span>
<span style="color: #666666;">// When Ruby makes a method call, it stores the origin class in the</span>
<span style="color: #666666;">// current stack frame.  When Ruby calls into Rice, we grab the origin</span>
<span style="color: #666666;">// class from the stack frame, then pull the data out of the origin</span>
<span style="color: #666666;">// class.  The data item is then used to determine how to convert</span>
<span style="color: #666666;">// arguments and return type, how to handle exceptions, etc.</span></pre></div></div>

<p>Bear with me here as I still have a hard time keeping this straight in my mind. To help understand what exactly is going on here, I&#8217;ve made a graph showing all the relevant links between Rice, C++ and Ruby as made by this method.</p>
<p><img src="http://jameskilton.com/blog/wp-content/uploads/2010/02/method_data.png" alt="Graph showing how Rice hooks into Ruby" /></p>
<p>The steps define_method_with_data takes:</p>
<p>   1. Create a new class inside of the class we&#8217;re exposing (called the origin class).<br />
   2. Build a new two-element array that has [ 0xDA7A, VALUE pointer to Auto_..._Wrapper class]<br />
   3. Give the origin class an easily recognized name (which is also an invalid Ruby constant name, preventing it from every being accidentally used in Ruby code, but it prints out in object dumps on occasion).<br />
   4. Set this origin class to be FT_SINGLETON which hides it from the user<sup><a href="http://jameskilton.com/2010/02/23/how-rice-works/#footnote_0_227" id="identifier_0_227" class="footnote-link footnote-identifier-link" title="http://blade.nagaokaut.ac.jp/cgi-bin/scat.rb/ruby/ruby-talk/336728">1</a></sup>.<br />
   5. Set a hidden ivar on the class that&#8217;s the array built in step 2<br />
   6. Define a method on the origin class that links to Auto_&#8230;_Wrapper::call with the requested name</p>
<p>At this point we&#8217;ve got everything ready except for actually being able to call the method from Ruby. These next steps were hard to show right on the graph because Rice actually modifies the symbol table of the base class in question.</p>
<p>  7. Create an alias on the origin class that aliases the method to &#8220;dummy&#8221;<br />
  8. Find this new alias entry in the origin class&#8217; symbol table<br />
  9. Modify the symbol table of the base class to call &#8220;dummy&#8221; on the origin class on any call to the method being wrapped.</p>
<p>We&#8217;ve now got everything hooked up: we have the c-style function hooked into Ruby and we have a way to access the actual Auto_&#8230;_Wrapper class once call() gets called. Now, you may be asking why this is such a complicated process when it could be done with a simple rb_define_method on Auto_&#8230;_Wrapper::call(). The answer to this question is show in the image above, there&#8217;s data and information saved in this Auto_&#8230;_Wrapper object that Rice needs to be able to properly convert argument and return types, and handle any exceptions that may get thrown.</p>
<p>With that, we&#8217;re done with the wrapping and exposing path through Rice. Now it&#8217;s time to head back up the chain and see how Rice handles calls from Ruby and passing execution back up into C++.</p>
<h4>Auto_&#8230;_Wrapper::call()</h4>
<p>It&#8217;s time to take a detailed look at this method. In short, once execution enters this method, it&#8217;s now Rice&#8217;s job to convert VALUE arguments into the appropriate C++ types, execute the wrapped method / function, then do any required conversion of return values back to VALUEs for Ruby, while also making sure that any exceptions that throw along the way are properly caught and handled (an uncaught exception in C++ will give you a SegmentationFault or a BusError. Always fun to debug).</p>
<p>So, first things first, we need to get back the Auto_&#8230;_Wrapper object we saved when we wrapped this function. This is done with the detail::method_data() function, details of which are easily seen and understood in detail/method_data.cpp. With this we run our arguments list through rb_scan_args then run through each argument and check if there&#8217;s was a default set in the wrapper and if we should use it (Side note: the sanitize<> template is a no-op right now and can be ignored. It&#8217;s there to attempt to clean out any references or const arguments that may come in to get the base type, but this was causing crashes on other wrappers. For now I assume there&#8217;s a possibility of a small memory leak here related to reference types). Once all the types are converted it&#8217;s time to actually call the C++ method or function, and handle the return type. </p>
<p>The noticeable difference between Auto_Member_Function_Wrapper and Auto_Function_Wrapper is that Auto_Function_Wrapper has some special handling for the &#8220;self&#8221; parameter. This functionality is here to support the ability to wrap C functions that are written in an OO way, such as:</p>

<div class="wp_syntax"><div class="code"><pre class="c" style="font-family:monospace;">Jukebox<span style="color: #339933;">*</span> newJukebox<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #993333;">void</span> play<span style="color: #009900;">&#40;</span>Jukebox<span style="color: #339933;">*</span> jukebox<span style="color: #339933;">,</span> Song<span style="color: #339933;">*</span> song<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #993333;">void</span> stop<span style="color: #009900;">&#40;</span>Jukebox<span style="color: #339933;">*</span> jukebox<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #993333;">void</span> addSong<span style="color: #009900;">&#40;</span>Jukebox<span style="color: #339933;">*</span> jukebox<span style="color: #339933;">,</span> Song<span style="color: #339933;">*</span> song<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #666666; font-style: italic;">// etc.</span></pre></div></div>

<p>Because of the special self handling of Auto_Function_Wrapper, these methods can be wrapped into a Jukebox class very simply:</p>

<div class="wp_syntax"><div class="code"><pre class="cpp" style="font-family:monospace;">define_class<span style="color: #008000;">&#40;</span><span style="color: #FF0000;">&quot;Jukebox&quot;</span><span style="color: #008000;">&#41;</span>.
  <span style="color: #007788;">define_method</span><span style="color: #008000;">&#40;</span><span style="color: #FF0000;">&quot;initialize&quot;</span>, <span style="color: #000040;">&amp;</span>newJukebox<span style="color: #008000;">&#41;</span>.
  <span style="color: #007788;">define_method</span><span style="color: #008000;">&#40;</span><span style="color: #FF0000;">&quot;play&quot;</span>, <span style="color: #000040;">&amp;</span>play<span style="color: #008000;">&#41;</span>.
  <span style="color: #007788;">define_method</span><span style="color: #008000;">&#40;</span><span style="color: #FF0000;">&quot;stop&quot;</span>, <span style="color: #000040;">&amp;</span>stop<span style="color: #008000;">&#41;</span>.
  <span style="color: #007788;">define_method</span><span style="color: #008000;">&#40;</span><span style="color: #FF0000;">&quot;add_song&quot;</span>, <span style="color: #000040;">&amp;</span>addSong<span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span></pre></div></div>

<p>Other than this, the two classes are identical in functionality.</p>
<h4>Constructor</h4>
<p>Because constructors aren&#8217;t accessible via normal function pointers, Rice has to implement special handling of wrapping class constructors for proper instantiation. This is done through the Rice::Constructor class and the define_constructor method. The path here is mostly equivalent to define_method. Opening up Constructor.{hpp,ipp} you can see the same ::call() static method, with a much simpler body. Every Ruby object has a free slot accessible through DATA_PTR. It&#8217;s in this slot that C++ class instances are saved and used for type conversions as described next. Constructor::call creates this object and saves it in DATA_PTR for later use.</p>
<h4>Default Arguments</h4>
<p>The code for handling and managing Default Arguments is pretty easy to read, but how the syntax work is definitely cause for confusion. Pulled from Boost.Python&#8217;s implementation of this exact feature, this functionality uses the comma operator to string together Rice::Arg objects into a single Arguments object that&#8217;s then passed into the Wrapped_Function object for that method. Due to the fact the comma operator doesn&#8217;t even come into play if there&#8217;s a single argument to a method, I was forced to copy some functionality around to make this feature work in all situations. So where you see two methods, one which takes a Rice::Arguments* and one which takes a Rice::Arg*, that&#8217;s what&#8217;s going on. I hope to clean this up drastically in the near future.</p>
<h4>to_ruby / from_ruby</h4>
<p>The last piece of Rice&#8217;s functionality is the type conversion system, exposed to the user through two methods: to_ruby(), which takes a C/C++ type and converts it to a VALUE, and from_ruby() which does the opposite. The signatures of these methods are simple:</p>

<div class="wp_syntax"><div class="code"><pre class="cpp" style="font-family:monospace;"><span style="color: #0000ff;">template</span><span style="color: #000080;">&lt;</span><span style="color: #0000ff;">typename</span> T<span style="color: #000080;">&gt;</span>
T from_ruby<span style="color: #008000;">&#40;</span>Rice<span style="color: #008080;">::</span><span style="color: #007788;">Object</span> x<span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
&nbsp;
<span style="color: #0000ff;">template</span><span style="color: #000080;">&lt;</span><span style="color: #0000ff;">typename</span> T<span style="color: #000080;">&gt;</span>
Rice<span style="color: #008080;">::</span><span style="color: #007788;">Object</span> to_ruby<span style="color: #008000;">&#40;</span>T <span style="color: #0000ff;">const</span> <span style="color: #000040;">&amp;</span> x<span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span></pre></div></div>

<p>For most basic and fundamental types, the to_/from_ruby implementations are very simple and can be seen in to_from_ruby.ipp, but this is only half of the story.</p>
<p>Rice&#8217;s real strength comes in handling custom-defined C++ types and seamlessly converting them from Ruby to C++ and back again, making sure to handle inheritance (both C++ &lt;=&gt; C++ and C++ &lt;=&gt; Ruby) appropriately. The core of this functionality is found in Data_Type::from_ruby in Data_Type.ipp, and in the Rice::Caster class found in detail/Caster.hpp, but it begins at the end of Data_Type::bind, which creates a new Caster for the newly bound type:</p>

<div class="wp_syntax"><div class="code"><pre class="cpp" style="font-family:monospace;">  detail<span style="color: #008080;">::</span><span style="color: #007788;">Abstract_Caster</span> <span style="color: #000040;">*</span> base_caster <span style="color: #000080;">=</span> Data_Type<span style="color: #000080;">&lt;</span>Base_T<span style="color: #000080;">&gt;</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span>.<span style="color: #007788;">caster</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
  caster_.<span style="color: #007788;">reset</span><span style="color: #008000;">&#40;</span><span style="color: #0000dd;">new</span> detail<span style="color: #008080;">::</span><span style="color: #007788;">Caster</span><span style="color: #000080;">&lt;</span>T, Base_T<span style="color: #000080;">&gt;</span><span style="color: #008000;">&#40;</span>base_caster, klass<span style="color: #008000;">&#41;</span><span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
  Data_Type_Base<span style="color: #008080;">::</span><span style="color: #007788;">casters</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span>.<span style="color: #007788;">insert</span><span style="color: #008000;">&#40;</span>std<span style="color: #008080;">::</span><span style="color: #007788;">make_pair</span><span style="color: #008000;">&#40;</span>klass, caster_.<span style="color: #007788;">get</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">&#41;</span></pre></div></div>

<p>Caster is at the core very simple. It&#8217;s a class that enables Rice to build a tree of Casters that define how to cast from a Ruby type into a custom C++ type. The code above is simply building a new Caster linking the new type to the Ruby class, specifying any superclass type as needed, then registering this Caster with Rice&#8217;s Caster tree. From here it&#8217;s time to look at how Rice uses this Caster list in Data_Type::from_ruby() (which btw is called through ::convert() in detail/from_ruby.{hpp,ipp}).</p>
<p>In the case that the C++ type we want is exactly the Ruby type we&#8217;ve been given, casting is easy, make a new Data_Object for that type and get the pointer. If this doesn&#8217;t match, then we need to start heading up the inheritance heirarchy (rb_mod_ancestors) looking for the <strong>lowest</strong> class in the hierarchy bound in Rice, get it&#8217;s Caster and attempt to cast into C++. This functionality allows any depth of inheritance to work seamlessly in Rice.</p>
<h3>The Future of Rice</h3>
<p>Rice is currently a very capable library, and is being used successfully by a couple of projects, but it does have a long way to go to be the SWIG replacement (along with my rb++ suite) I want it to be. For the next release of Rice I&#8217;m current planning on the following work:</p>
<ul>
<li>Refactoring Auto_{,Member}_Function_Wrapper, Constructor, wrap_function, et.al. to be much simpler. Going to try to abstract out the actual method dispatch into a class like Auto_Functor_Wrapper which will handle all the to_/from_ruby and argument management magic.</li>
<li>Default arguments on Constructor. To do this Constructor needs to act more like an Auto_Function_Wrapper, and thus would be much easier to implement once the refactoring above is done.</li>
<li>Beginning into a def_helper (from Boost.Python) feature. Right now the implementation of default arguments is pretty messy. As I need to handle multiple arguments as well as a single argument, I&#8217;ve resorted to two define_method implementations to take these two cases. With some template magic, I can make it work with a single argument, as well as opening up a single place for call and return policy functionality, instead of multiple places that would be required today.</li>
</ul>
<p>As always, I&#8217;m available over Github messages / Issues, Email, comments here, or on Rice&#8217;s mailing list (rice AT librelist DOT com). I&#8217;ve also got a public tracker up on Pivotal: <a href="http://www.pivotaltracker.com/projects/48783">http://www.pivotaltracker.com/projects/48783</a>, but not sure how well that&#8217;s going to work for a free-time project such as this, though keeping a some-what strict time line is probably good for me, but I digress.</p>
<ol class="footnotes"><li id="footnote_0_227" class="footnote"><a href="http://blade.nagaokaut.ac.jp/cgi-bin/scat.rb/ruby/ruby-talk/336728">http://blade.nagaokaut.ac.jp/cgi-bin/scat.rb/ruby/ruby-talk/336728</a></li></ol>]]></content:encoded>
			<wfw:commentRss>http://jameskilton.com/2010/02/23/how-rice-works/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

