<ppdoc>
<copyright>
    Copyright (c) 2001 by Addison Wesley Longman.  This
    material may be distributed only subject to the terms and
    conditions set forth in the Open Publication License, v1.0 or
    later (the latest version is presently available at
    http://www.opencontent.org/openpub/).
</copyright>
<chapter  ref="xref-000001" name="Extending Ruby">
<p/>
It
is easy to extend Ruby with new features by writing code in Ruby.
Once you start adding in low-level code written in C, however, the
possibilities are endless.  
<p/>
Extending Ruby with C is pretty easy.  For instance, suppose we are
building a custom Internet-ready jukebox for the Sunset Diner and
Grill.  It will play MP3 audio files from a hard disk or audio CDs
from a CD jukebox.  We want to be able to control the jukebox hardware
from a Ruby program.  The hardware vendor gave us a C header file and
a binary library to use; our job is to construct a Ruby object
that makes the appropriate C function calls.
<p/>
But before we can get Ruby and C to work together, we need to see what
the Ruby world looks like from the C side.<footnote>Much of the
  information in this chapter is taken from the <tt>README.EXT</tt>
  file that is included in the distribution.  If you are planning on
  writing a Ruby extension, you may want to refer to that file for
  more details as well as the latest changes.</footnote>
<section>Ruby Objects in C</section>
<p/>
The first thing we need to look at is how to represent and access Ruby
datatypes from within C.
Everything in Ruby is an object, and all
variables are references to objects.  In C, this means that the type
of all Ruby variables is <tt>VALUE</tt>,
which is either a pointer to a Ruby object or an immediate value (such
as <tt>Fixnum</tt>).
<p/>
This is how Ruby implements object-oriented code in C: a Ruby object
is an allocated structure in memory that contains a table of instance
variables and information about the class.  The class itself is
another object (an allocated structure in memory) that contains a
table of the methods defined for that class. On this foundation hangs
all of Ruby.
<subsection><sansfont>VALUE</sansfont> as a Pointer</subsection>
When <tt>VALUE</tt> is a pointer, it is a pointer to one of the 
defined Ruby object structures---you can't have a <tt>VALUE</tt> that points to an
arbitrary structure.  The structures for each built-in
class are defined in ``<tt>ruby.h</tt>''
and are named <tt>R</tt><em>Classname</em>, as in <tt>RString</tt> and
<tt>RArray</tt>.  
<p/>
You can check to see what type of structure is used for a particular
<tt>VALUE</tt> in a number of ways. The macro <tt>TYPE(</tt><em>obj</em><tt>)</tt>
will return a constant representing the C
type of the given object: <tt>T_OBJECT</tt>, <tt>T_STRING</tt>, and so on.
Constants for the built-in classes are defined in ``<tt>ruby.h</tt>''.
Note that the <em>type</em> we are referring to here is an
implementation detail---it is not the same as the class of an object.
<p/>
If you want to ensure that a value pointer points to a particular
structure, you can use the macro <tt>Check_Type</tt>, which will raise a
<exception>TypeError</exception> exception if <em>value</em> is not of the expected
<em>type</em> (which is one of the constants <tt>T_STRING</tt>,
<tt>T_FLOAT</tt>, and so on):
<p/>
<alltt>
Check_Type(VALUE <em>value</em>, int <em>type</em>)
</alltt>
<p/>
If speed is an issue, there are faster macros that check specifically
for the immediate values <tt>Fixnum</tt> and <tt>nil</tt>.
<p/>
<alltt>
FIXNUM_P(<em>value</em>) <returns>non-zero if value is a Fixnum</returns>
NIL_P(<em>value</em>)    <returns>non-zero if value is nil</returns>
RTEST(<em>value</em>)    <returns>non-zero if value is neither nil nor false</returns>
</alltt>
<p/>
Again, note that we are talking about ``type'' as the C structure that
represents a particular built-in type.  The class of an object is a
different beast entirely.  The class objects for the built-in classes
are stored in C global variables named <tt>rb_c</tt><em>Classname</em>
(for instance, <tt>rb_cObject</tt>); modules are named
<tt>rb_m</tt><em>Modulename</em>.
<p/>
It wouldn't be advisable to mess with the data in these
structures directly, however---you may look, but don't touch unless
you are fond of debuggers.  You should normally use only the supplied 
C functions to manipulate Ruby data (we'll talk more about this in just
a moment).
<p/>
However, in the interests of efficiency you may need to dig into these
structures to obtain data.  In order to dereference members of these C
structures, you have to cast the generic <tt>VALUE</tt> to the proper
structure type.  <tt>ruby.h</tt> contains a number of macros that perform
the proper casting for you, allowing you to dereference structure
members easily. These macros are named
<tt>R<em>CLASSNAME</em></tt>, as in <tt>RSTRING</tt> or <tt>RARRAY</tt>.  For
example:
<p/>
<alltt>
VALUE str, arr;
RSTRING(str)-&gt;len <returns>length of the Ruby string</returns>
RSTRING(str)-&gt;ptr <returns>pointer to string storage</returns>
RARRAY(arr)-&gt;len  <returns>length of the Ruby array</returns>
RARRAY(arr)-&gt;capa <returns>capacity of the Ruby array</returns>
RARRAY(arr)-&gt;ptr  <returns>pointer to array storage</returns>
</alltt>
<subsection><sansfont>VALUE</sansfont> as an Immediate Object</subsection>
<p/>
As we said above, immediate values are not pointers: <tt>Fixnum</tt>,
<tt>Symbol</tt>, <tt>true</tt>, <tt>false</tt>, and <tt>nil</tt> are stored directly in
<tt>VALUE</tt>.
<p/>
<tt>Fixnum</tt> values are stored as 31-bit numbers<footnote>Or 63-bit on
  wider CPU architectures.</footnote> that are formed by shifting the original
number left 1 bit and then setting the least significant bit (bit
0) to ``1.''  When <tt>VALUE</tt> is used as a pointer to a specific Ruby
structure, it is guaranteed always to have an LSB of zero; the
other immediate values also have LSBs of zero. Thus, a simple
bit test can tell you whether or not you have a <tt>Fixnum</tt>.
<p/>
There are several useful conversion macros for numbers as well as
other standard datatypes shown in Table 17.1 on page 174.
<p/>
The other immediate values (<kw>true</kw>, <kw>false</kw>, and <tt>nil</tt>) are
represented in C as the constants <kw>Qtrue</kw>, <kw>Qfalse</kw>, and
<kw>Qnil</kw>, respectively.  You can test <tt>VALUE</tt> variables against
these constants directly, or use the conversion macros (which perform
the proper casting).
<section>Writing Ruby in C</section>
<p/>
One of the joys of Ruby is that you can write Ruby programs almost
directly in C.  That is, you can use the same methods and the same
logic, but with slightly different syntax to accommodate C.  For
instance, here is a small, fairly boring test class written in Ruby.
<p/>
<codefragment>
<alltt><fullcode><![CDATA[  class Test
    def initialize
      @arr = Array.new
    end
    def add(anObject)
      @arr.push(anObject)
    end
  end
]]></fullcode>
class<nbsp/>Test
<nbsp/><nbsp/>def<nbsp/>initialize
<nbsp/><nbsp/><nbsp/><nbsp/>@arr<nbsp/>=<nbsp/>Array.new
<nbsp/><nbsp/>end
<nbsp/><nbsp/>def<nbsp/>add(anObject)
<nbsp/><nbsp/><nbsp/><nbsp/>@arr.push(anObject)
<nbsp/><nbsp/>end
end
</alltt>
</codefragment>
<p/>
The equivalent code in C should look somewhat familiar.
<p/>
<codefragment>
<alltt><fullcode><![CDATA[#include "ruby.h"

static VALUE t_init(VALUE self)
{
  VALUE arr;

  arr = rb_ary_new();
  rb_iv_set(self, "@arr", arr);
  return self;
}

static VALUE t_add(VALUE self, VALUE anObject)
{
  VALUE arr;

  arr = rb_iv_get(self, "@arr");
  rb_ary_push(arr, anObject);
  return arr;
}

VALUE cTest;

void Init_Test() {
  cTest = rb_define_class("Test", rb_cObject);
  rb_define_method(cTest, "initialize", t_init, 0);
  rb_define_method(cTest, "add", t_add, 1);
}
]]></fullcode>
#include<nbsp/>"ruby.h"
<p/>
static<nbsp/>VALUE<nbsp/>t_init(VALUE<nbsp/>self)
{
<nbsp/><nbsp/>VALUE<nbsp/>arr;
<p/>
<nbsp/><nbsp/>arr<nbsp/>=<nbsp/>rb_ary_new();
<nbsp/><nbsp/>rb_iv_set(self,<nbsp/>"@arr",<nbsp/>arr);
<nbsp/><nbsp/>return<nbsp/>self;
}
<p/>
static<nbsp/>VALUE<nbsp/>t_add(VALUE<nbsp/>self,<nbsp/>VALUE<nbsp/>anObject)
{
<nbsp/><nbsp/>VALUE<nbsp/>arr;
<p/>
<nbsp/><nbsp/>arr<nbsp/>=<nbsp/>rb_iv_get(self,<nbsp/>"@arr");
<nbsp/><nbsp/>rb_ary_push(arr,<nbsp/>anObject);
<nbsp/><nbsp/>return<nbsp/>arr;
}
<p/>
VALUE<nbsp/>cTest;
<p/>
void<nbsp/>Init_Test()<nbsp/>{
<nbsp/><nbsp/>cTest<nbsp/>=<nbsp/>rb_define_class("Test",<nbsp/>rb_cObject);
<nbsp/><nbsp/>rb_define_method(cTest,<nbsp/>"initialize",<nbsp/>t_init,<nbsp/>0);
<nbsp/><nbsp/>rb_define_method(cTest,<nbsp/>"add",<nbsp/>t_add,<nbsp/>1);
}
</alltt>
</codefragment>
<p/>
Let's go through this example in detail, as it illustrates many of the
important concepts in this chapter.  First off, we need to include the
header file ``<tt>ruby.h</tt>'' to obtain the necessary definitions.
<p/>
Now look at the last function, <tt>Init_Test</tt>.
Every class or module
defines a C global function named <tt>Init_</tt><em>Name</em>.  This
function will be called when the interpreter first loads the extension
<em>Name</em> (or on startup for statically linked extensions). It is
used to initialize the extension and to insinuate it into the Ruby
environment.  In this case, we define a new class named <tt>Test</tt>,
which is a subclass of <tt>Object</tt> (represented by the external symbol
<tt>rb_cObject</tt>; see ``<tt>ruby.h</tt>'' for others).
<p/>
Next we set up <tt>add</tt> and <tt>initialize</tt> as two instance methods
for class <tt>Test</tt>.
The calls to <tt>rb_define_method</tt> establish
a binding between the Ruby method name and the C function that will
implement it, so a call to the <tt>add</tt> method in Ruby will call the
C function <tt>t_add</tt> with one argument.
<p/>
Similarly, when <tt>new</tt> is called for this class, Ruby will construct
a basic object and then call <tt>initialize</tt>, which we have defined
here to call the C function <tt>t_init</tt> with no (Ruby) arguments.
<p/>
Now go back and look at the definition of <tt>initialize</tt>.  Even
though we said it took no arguments, there's a parameter here!  In
addition to any Ruby arguments, every method is passed an initial
<tt>VALUE</tt> argument that contains the receiver for this method (the
equivalent of <const>self</const> in Ruby code).
<p/>
The first thing we'll do in <tt>initialize</tt> is create a Ruby array
and set the instance variable <tt>@arr</tt> to point to it.  Just as you
would expect if you were writing Ruby source, referencing an instance
variable that doesn't exist creates it.
<p/>
Finally, the function <tt>t_add</tt> gets the instance variable <tt>@arr</tt>
from the current object and calls <cim><file>array</file><front>Array</front><back>push</back><mref>push</mref></cim> to push the passed value
onto that array.  When accessing instance variables in this way, the
<tt>@</tt>-prefix is mandatory---otherwise the variable is created, but
cannot be referenced from Ruby.
<p/>
Despite the extra, clunky syntax that C imposes, you're still writing
in Ruby---you can manipulate objects using all of the method calls 
you've come to know and love, with the added advantage of being able
to craft tight, fast code when needed.
<p/>
<b>WARNING:</b> Every C function that is callable from Ruby
<em>must</em> return a <tt>VALUE</tt>, even if it's just <const>Qnil</const>.
Otherwise, a core dump (or GPF) will be the likely result.
<p/>
We can use the C version of the code in Ruby simply
by <kw>require</kw>-ing it dynamically at runtime (on
most platforms).
<p/>
<codefragment>
<alltt><fullcode><![CDATA[  require "code/ext/Test"
  t = Test.new
  t.add("Bill Chase")
]]></fullcode>
require<nbsp/>"code/ext/Test"
t<nbsp/>=<nbsp/>Test.new
t.add("Bill<nbsp/>Chase")
</alltt>
</codefragment>
<figure type="table">
<caption>C/Ruby datatype conversion functions and
  macros</caption>
<table>
<th>
<td colspan="3"><b>C Datatypes to Ruby Objects:</b></td>
</th>
<tr>
  <td></td>
  <td>INT2NUM(<em>int</em>)</td>
  <td><returns><em>Fixnum</em> or <em>Bignum</em></returns></td>
</tr>
<tr>
  <td></td>
  <td>INT2FIX(<em>int</em>)</td>
  <td><returns><em>Fixnum</em></returns> (faster)</td>
</tr>
<tr>
  <td></td>
  <td>INT2NUM(<em>long</em> or <em>int</em>)</td>
  <td><returns><em>Fixnum</em> or <em>Bignum</em></returns></td>
</tr>
<tr>
  <td></td>
  <td>INT2FIX(<em>long</em> or <em>int</em>)</td>
  <td><returns><em>Fixnum</em></returns> (faster)</td>
</tr>
<tr>
  <td></td>
  <td>CHR2FIX(<em>char</em>)</td>
  <td><returns><em>Fixnum</em></returns></td>
</tr>
<tr>
  <td></td>
  <td>rb_str_new2(<em>char *</em>)</td>
  <td><returns><em>String</em></returns></td>
</tr>
<tr>
  <td></td>
  <td>rb_float_new(<em>double</em>)</td>
  <td><returns><em>Float</em></returns></td>
</tr>
<toprule/><tr>
<td colspan="3"><b>Ruby Objects to C Datatypes:</b></td>
</tr>
<th>
  <td>int</td>
  <td>NUM2INT(<em>Numeric</em>)</td>
  <td>(Includes type check)</td>
</th>
<th>
  <td>int</td>
  <td>FIX2INT(<em>Fixnum</em>)</td>
  <td>(Faster)</td>
</th>
<th>
  <td>unsigned int</td>
  <td>NUM2UINT(<em>Numeric</em>)</td>
  <td>(Includes type check)</td>
</th>
<th>
  <td>unsigned int</td>
  <td>FIX2UINT(<em>Fixnum</em>)</td>
  <td>(Includes type check)</td>
</th>
<th>
  <td>long</td>
  <td>NUM2LONG(<em>Numeric</em>)</td>
  <td>(Includes type check)</td>
</th>
<th>
  <td>long</td>
  <td>FIX2LONG(<em>Fixnum</em>)</td>
  <td>(Faster)</td>
</th>
<th>
  <td>unsigned long</td>
  <td>NUM2ULONG(<em>Numeric</em>)</td>
  <td>(Includes type check)</td>
</th>
<th>
  <td>char</td>
  <td>NUM2CHR(<em>Numeric</em> or <em>String</em>)</td>
  <td>(Includes type check)</td>
</th>
<th>
  <td>char *</td>
  <td>STR2CSTR(<em>String</em>)</td>
  <td></td>
</th>
<th>
  <td>char *</td>
  <td>rb_str2cstr(<em>String</em>, int *length)</td>
  <td>Returns length as well</td>
</th>
<th>
  <td>double</td>
  <td>NUM2DBL(<em>Numeric</em>)</td>
  <td></td>
</th>
<bottomrule/></table>
<p/>
</figure>
<p/>
<subsection>Evaluating Ruby Expressions in C</subsection>
<p/>
If you are in the middle of some C code and you want to run an
arbitrary Ruby expression without writing a bunch of C, you can always
use the C version of <tt>eval</tt>. Suppose you have a collection of
objects that need to have a flag cleared.
<p/>
<codefragment>
<alltt><fullcode><![CDATA[  rb_eval_string("anObject.each{|x| x.clearFlag }");
]]></fullcode>
rb_eval_string("anObject.each{|x|<nbsp/>x.clearFlag<nbsp/>}");
</alltt>
</codefragment>
<p/>
If you just want to call a particular method (which is cheaper than
<tt>eval</tt>-ing an entire string) you can use
<p/>
<codefragment>
<alltt><fullcode><![CDATA[  rb_funcall(receiver, method_id, argc, ...)
]]></fullcode>
rb_funcall(receiver,<nbsp/>method_id,<nbsp/>argc,<nbsp/>...)
</alltt>
</codefragment>
<p/>
Full descriptions of these and other commonly used C functions begin
on page 186.
<section>Sharing Data Between Ruby and C</section>
<p/>
We've covered enough of the basics now to return to our jukebox
example---interfacing C code with Ruby and sharing data and behavior
between the two worlds.
<subsection>Directly Sharing Variables</subsection>
<p/>
Although you could maintain a C version of some variable along with a
separate Ruby version of that variable, and struggle to keep the two
in sync,<footnote>A clear violation of the <em>DRY</em>--Don't
  Repeat Yourself---principle described in our book <em>The Pragmatic
    Programmer</em><nbsp/>.</footnote> it would be much better to
share a variable directly between Ruby and C.
You can share global
variables by creating a Ruby object on the C side and then binding
its address to a Ruby global variable.  In this case, the $ prefix is
optional, but it helps clarify that this is a global variable.
<p/>
<codefragment>
<alltt><fullcode><![CDATA[  VALUE hardware_list;
  hardware_list = rb_ary_new();
  rb_define_variable("$hardware", &hardware_list);
  ...
  rb_ary_push(hardware_list, rb_str_new2("DVD"));
  rb_ary_push(hardware_list, rb_str_new2("CDPlayer1"));
  rb_ary_push(hardware_list, rb_str_new2("CDPlayer2"));
]]></fullcode>
VALUE<nbsp/>hardware_list;
hardware_list<nbsp/>=<nbsp/>rb_ary_new();
rb_define_variable("$hardware",<nbsp/>&amp;hardware_list);
...
rb_ary_push(hardware_list,<nbsp/>rb_str_new2("DVD"));
rb_ary_push(hardware_list,<nbsp/>rb_str_new2("CDPlayer1"));
rb_ary_push(hardware_list,<nbsp/>rb_str_new2("CDPlayer2"));
</alltt>
</codefragment>
<p/>
The Ruby side can then access the C variable <tt>hardware_list</tt> as
<tt>$hardware</tt>:
<p/>
<codefragment>
<fullcode><![CDATA[!-    $hardware = [ "DVD", "CDPlayer1", "CDPlayer2" ]
  $hardware
]]></fullcode><rubycode>
<tr>
  <td><tt>$hardware</tt></td>
  <td>&#187;</td>
  <td><tt>["DVD",<nbsp/>"CDPlayer1",<nbsp/>"CDPlayer2"]</tt></td>
</tr>
</rubycode>
<p/>
</codefragment>
<p/>
You can also create <em>hooked</em>
variables that will call a specified function when the variable is
accessed, and <em>virtual</em> variables that only call the hooks---no
actual variable is involved.  See the API section that begins
on page 189 for details.
<p/>
If you create a Ruby object from C and store it in a C global
variable
<em>without</em> exporting it to Ruby, you must at least tell the
garbage collector about it, lest ye be reaped inadvertently:
<p/>
<codefragment>
<alltt><fullcode><![CDATA[  VALUE obj;
  obj = rb_ary_new();
  rb_global_variable(obj);
]]></fullcode>
VALUE<nbsp/>obj;
obj<nbsp/>=<nbsp/>rb_ary_new();
rb_global_variable(obj);
</alltt>
</codefragment>
<subsection>Wrapping C Structures</subsection>
Now on to the <em>really</em> fun stuff.  We've got the vendor's
library that controls the audio CD jukebox units, and we're ready to
wire it into Ruby.  The vendor's header file looks like this:
<p/>
<codefragment>
<alltt><fullcode><![CDATA[typedef struct _cdjb {
  int statusf;
  int request;
  void *data;
  char pending;
  int unit_id;
  void *stats;
} CDJukebox;

// Allocate a new CDPlayer structure and bring it online
CDJukebox *CDPlayerNew(int unit_id);

// Deallocate when done (and take offline)
void CDPlayerDispose(CDJukebox *rec);

// Seek to a disc, track and notify progress
void CDPlayerSeek(CDJukebox *rec, 
                  int disc, 
                  int track,
                  void (*done)(CDJukebox *rec, int percent));
// ... others...
// Report a statistic
double CDPlayerAvgSeekTime(CDJukebox *rec);
]]></fullcode>
typedef<nbsp/>struct<nbsp/>_cdjb<nbsp/>{
<nbsp/><nbsp/>int<nbsp/>statusf;
<nbsp/><nbsp/>int<nbsp/>request;
<nbsp/><nbsp/>void<nbsp/>*data;
<nbsp/><nbsp/>char<nbsp/>pending;
<nbsp/><nbsp/>int<nbsp/>unit_id;
<nbsp/><nbsp/>void<nbsp/>*stats;
}<nbsp/>CDJukebox;
<p/>
//<nbsp/>Allocate<nbsp/>a<nbsp/>new<nbsp/>CDPlayer<nbsp/>structure<nbsp/>and<nbsp/>bring<nbsp/>it<nbsp/>online
CDJukebox<nbsp/>*CDPlayerNew(int<nbsp/>unit_id);
<p/>
//<nbsp/>Deallocate<nbsp/>when<nbsp/>done<nbsp/>(and<nbsp/>take<nbsp/>offline)
void<nbsp/>CDPlayerDispose(CDJukebox<nbsp/>*rec);
<p/>
//<nbsp/>Seek<nbsp/>to<nbsp/>a<nbsp/>disc,<nbsp/>track<nbsp/>and<nbsp/>notify<nbsp/>progress
void<nbsp/>CDPlayerSeek(CDJukebox<nbsp/>*rec,
<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>int<nbsp/>disc,
<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>int<nbsp/>track,
<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>void<nbsp/>(*done)(CDJukebox<nbsp/>*rec,<nbsp/>int<nbsp/>percent));
//<nbsp/>...<nbsp/>others...
//<nbsp/>Report<nbsp/>a<nbsp/>statistic
double<nbsp/>CDPlayerAvgSeekTime(CDJukebox<nbsp/>*rec);
</alltt>
</codefragment>
<p/>
This vendor has its act together; while the vendor might not admit it, the
code is written with an object-oriented flavor.  We don't know what
all those fields mean within the <tt>CDJukeBox</tt> structure, but that's
okay---we can treat it as an opaque pile of bits.  The vendor's code 
knows what to do with it, we just have to carry it around.
<p/>
Anytime you have a C-only structure that you would like to handle as a
Ruby object, you should wrap it in a special, internal Ruby class
called <tt>DATA</tt> (type <tt>T_DATA</tt>).
There are two macros to do this wrapping, and one to retrieve your
structure back out again.
<p/>
 <table>
      <cdoctitle>C Datatype Wrapping</cdoctitle>
      <cfunc name="Data_Wrap_Struct">
    <creturns>VALUE</creturns>
        <cparams>VALUE<nbsp/>class, void<nbsp/>(*mark)(),
   void<nbsp/>(*free)(), void<nbsp/>*ptr"</cparams>
        <cbody>    Wraps the given C datatype <em>ptr</em>, registers the
    two garbage collection routines (see below), and returns 
    a VALUE pointer to a genuine Ruby object.  The C type of the
    resulting object is <tt>T_DATA</tt> and its Ruby class is <em>class</em>.
  </cbody>
      </cfunc>
  <cfunc name="Data_Make_Struct">
    <creturns>VALUE</creturns>
        <cparams>VALUE<nbsp/>class, <em>c-type</em>,
    void<nbsp/>(*mark)(), void<nbsp/>(*free)(), <em>c-type *</em>"</cparams>
        <cbody>    Allocates a structure of the indicated
    type first, then proceeds as <tt>Data_Wrap_Struct</tt>. <em>c-type</em>
    is the name of the C datatype that you're wrapping, not a
    variable of that type.
  </cbody>
      </cfunc>
  <cfunc name="Data_Get_Struct">
    <creturns></creturns>
        <cparams>VALUE<nbsp/>obj,<em>c-type</em>,<em>c-type *</em>"</cparams>
        <cbody>    Returns the original pointer.  This macro 
    is a type-safe wrapper around the macro
    <tt>DATA_PTR(obj)</tt>, which evaluates the pointer.
  </cbody>
      </cfunc>
<p/>
     </table>
<p/>
The object created by <tt>Data_Wrap_Struct</tt> is a normal Ruby object,
except that it has an additional C datatype that can't be accessed
from Ruby.  As you can see in Figure 17.1 on page 177, this C
datatype is separate from any instance variables that the object
contains.
But since it's a separate thing, how do you get rid of it when the
garbage collector claims this object?  What if you have to release
some resource (close some file, clean up some lock or IPC mechanism,
and so on)?
<figure type="figure">Figure not available...</figure>
<p/>
In order to participate in Ruby's mark-and-sweep garbage collection process,
you need to define a
routine to free your structure, and possibly a routine to mark any
references from your structure to other structures. Both routines take a <tt>void</tt>
pointer, a reference to your structure.
The <em>mark</em> routine will be called by the garbage collector
during its ``mark'' phase.  If your structure references other Ruby
objects, then your mark function needs to identify these objects using
<tt>rb_gc_mark(<em>value</em>)</tt>.  If the structure doesn't reference
other Ruby objects, you can simply pass <tt>0</tt> as a function pointer.
<p/>
When the object needs to be disposed of, the garbage collector will
call the <em>free</em> routine to free it.  If you have allocated any
memory yourself (for instance, by using <tt>Data_Make_Struct</tt>),
you'll need to pass a free function---even if it's just the standard C
library's <tt>free</tt> routine.  For complex structures that you have
allocated, your free function may need to traverse the structure to
free all the allocated memory.
<p/>
First a simple example, without any special handling.  Given the
structure definition
<p/>
<codefragment>
<alltt><fullcode><![CDATA[  typedef struct mp3info {
    char *title;
    char *artist;
    int  genre;
  } MP3Info;
]]></fullcode>
typedef<nbsp/>struct<nbsp/>mp3info<nbsp/>{
<nbsp/><nbsp/>char<nbsp/>*title;
<nbsp/><nbsp/>char<nbsp/>*artist;
<nbsp/><nbsp/>int<nbsp/><nbsp/>genre;
}<nbsp/>MP3Info;
</alltt>
</codefragment>
<p/>
we can create a structure, populate it, and wrap it as an
object.<footnote>We cheat a bit in this example. Our <tt>MP3Info</tt>
  structure has a couple of <tt>char</tt> pointers in it. In our code we
  initialize them from two static strings. This means that we don't
  have to free these strings when the <tt>MP3Info</tt> structure is freed.
  If we'd allocated these strings dynamically, we'd have to write a
  free method to dispose of them.</footnote>
<p/>
<codefragment>
<alltt><fullcode><![CDATA[    MP3Info *p;
    VALUE info;

    p = ALLOC(MP3Info);
    p->artist = "Maynard Ferguson";
    p->title = "Chameleon";
    ...
    info = Data_Wrap_Struct(cTest, 0, free, p);
]]></fullcode>
MP3Info<nbsp/>*p;
VALUE<nbsp/>info;
<p/>
p<nbsp/>=<nbsp/>ALLOC(MP3Info);
p-&gt;artist<nbsp/>=<nbsp/>"Maynard<nbsp/>Ferguson";
p-&gt;title<nbsp/>=<nbsp/>"Chameleon";
...
info<nbsp/>=<nbsp/>Data_Wrap_Struct(cTest,<nbsp/>0,<nbsp/>free,<nbsp/>p);
</alltt>
</codefragment>
<p/>
<tt>info</tt> is a <tt>VALUE</tt> type, a genuine Ruby object of class
<tt>Test</tt> (represented in C by the built-in type <tt>T_DATA</tt>). You
can push it onto an array, hold a reference to it in an object, and so
on.  At some later point in the code, we may want to access this
structure again, given the <tt>VALUE</tt>:
<p/>
<codefragment>
<alltt>
VALUE doit(VALUE info) {
  MP3Info *p;
  Data_Get_Struct(info, MP3Info, p);
  ...
  p-&gt;artist    <returns>"Maynard Ferguson"</returns>
  p-&gt;title     <returns>"Chameleon"</returns>
  ...
}
</alltt>
</codefragment>
<p/>
In order to follow convention, however, you may need a few more
things: support for an <meth>initialize</meth> method, and
a ``C-constructor.''  If you
were writing Ruby source, you'd allocate and initialize an object by
calling <meth>new</meth>. In C extensions, the corresponding call is
<tt>Data_Make_Struct</tt>.  However, although this allocates memory for
the object, it does <em>not</em> automatically call an <kw>initialize</kw>
method; you need to do that yourself:
<p/>
<codefragment>
<alltt><fullcode><![CDATA[    info = Data_Make_Struct(cTest, MP3Info, 0, free, one);
    rb_obj_call_init(info, argc, argv);
]]></fullcode>
info<nbsp/>=<nbsp/>Data_Make_Struct(cTest,<nbsp/>MP3Info,<nbsp/>0,<nbsp/>free,<nbsp/>one);
rb_obj_call_init(info,<nbsp/>argc,<nbsp/>argv);
</alltt>
</codefragment>
<p/>
This has the benefit of allowing subclasses in Ruby to override or
augment the basic <kw>initialize</kw> in your class.  Within
<kw>initialize</kw>, it is allowable (but not necessarily advisable) to
alter the existing data pointer, which may be accessed directly with
<tt>DATA_PTR(obj)</tt>.
<p/>
And finally, you may want to define a ``C-constructor''---that
is, a globally available C function that will
create the object in one convenient call.  You can use this function
within your own code or allow other extension libraries to use it.
All of the built-in classes support this idea with functions such as
<tt>rb_str_new</tt>, <tt>rb_ary_new</tt>, and so on.  We can make our own:
<p/>
<codefragment>
<alltt><fullcode><![CDATA[    VALUE mp3_info_new() {
      VALUE info;
      MP3Info *one;
      info = Data_Make_Struct(cTest, MP3Info, 0, free, one);
      ...
      rb_obj_call_init(info, 0, 0);
      return info;
    }
]]></fullcode>
VALUE<nbsp/>mp3_info_new()<nbsp/>{
<nbsp/><nbsp/>VALUE<nbsp/>info;
<nbsp/><nbsp/>MP3Info<nbsp/>*one;
<nbsp/><nbsp/>info<nbsp/>=<nbsp/>Data_Make_Struct(cTest,<nbsp/>MP3Info,<nbsp/>0,<nbsp/>free,<nbsp/>one);
<nbsp/><nbsp/>...
<nbsp/><nbsp/>rb_obj_call_init(info,<nbsp/>0,<nbsp/>0);
<nbsp/><nbsp/>return<nbsp/>info;
}
</alltt>
</codefragment>
<subsection>An Example</subsection>
<p/>
Okay, now we're ready for a full-size example.
Given our vendor's header file above, we write the following code.
<p/>
<codefragment>
<alltt><fullcode><![CDATA[#include "ruby.h"
#include "cdjukebox.h"

VALUE cCDPlayer;

static void cd_free(void *p) {
  CDPlayerDispose(p);
} 

static void progress(CDJukebox *rec, int percent) 
{
  if (rb_block_given_p()) {
    if (percent > 100) percent = 100;
    if (percent < 0) percent = 0;
    rb_yield(INT2FIX(percent));
  }
}

static VALUE
cd_seek(VALUE self, VALUE disc, VALUE track)
{
  CDJukebox *ptr;
  Data_Get_Struct(self, CDJukebox, ptr);

  CDPlayerSeek(ptr,
               NUM2INT(disc), 
               NUM2INT(track),
               progress);
  return Qnil;
}

static VALUE
cd_seekTime(VALUE self)
{
  double tm;
  CDJukebox *ptr;
  Data_Get_Struct(self, CDJukebox, ptr);
  tm = CDPlayerAvgSeekTime(ptr);
  return rb_float_new(tm);
} 

static VALUE
cd_unit(VALUE self)
{
  return rb_iv_get(self, "@unit");
}

static VALUE
cd_init(VALUE self, VALUE unit)
{
  rb_iv_set(self, "@unit", unit);
  return self;
}

VALUE cd_new(VALUE class, VALUE unit)
{
  VALUE argv[1];
  CDJukebox *ptr = CDPlayerNew(NUM2INT(unit));
  VALUE tdata = Data_Wrap_Struct(class, 0, cd_free, ptr);
  argv[0] = unit;
  rb_obj_call_init(tdata, 1, argv);
  return tdata;
}

void Init_CDJukebox() {
  cCDPlayer = rb_define_class("CDPlayer", rb_cObject);
  rb_define_singleton_method(cCDPlayer, "new", cd_new, 1);
  rb_define_method(cCDPlayer, "initialize", cd_init, 1);
  rb_define_method(cCDPlayer, "seek", cd_seek, 2);
  rb_define_method(cCDPlayer, "seekTime", cd_seekTime, 0);
  rb_define_method(cCDPlayer, "unit", cd_unit, 0);
}
]]></fullcode>
#include<nbsp/>"ruby.h"
#include<nbsp/>"cdjukebox.h"
<p/>
VALUE<nbsp/>cCDPlayer;
<p/>
static<nbsp/>void<nbsp/>cd_free(void<nbsp/>*p)<nbsp/>{
<nbsp/><nbsp/>CDPlayerDispose(p);
}
<p/>
static<nbsp/>void<nbsp/>progress(CDJukebox<nbsp/>*rec,<nbsp/>int<nbsp/>percent)
{
<nbsp/><nbsp/>if<nbsp/>(rb_block_given_p())<nbsp/>{
<nbsp/><nbsp/><nbsp/><nbsp/>if<nbsp/>(percent<nbsp/>&gt;<nbsp/>100)<nbsp/>percent<nbsp/>=<nbsp/>100;
<nbsp/><nbsp/><nbsp/><nbsp/>if<nbsp/>(percent<nbsp/>&lt;<nbsp/>0)<nbsp/>percent<nbsp/>=<nbsp/>0;
<nbsp/><nbsp/><nbsp/><nbsp/>rb_yield(INT2FIX(percent));
<nbsp/><nbsp/>}
}
<p/>
static<nbsp/>VALUE
cd_seek(VALUE<nbsp/>self,<nbsp/>VALUE<nbsp/>disc,<nbsp/>VALUE<nbsp/>track)
{
<nbsp/><nbsp/>CDJukebox<nbsp/>*ptr;
<nbsp/><nbsp/>Data_Get_Struct(self,<nbsp/>CDJukebox,<nbsp/>ptr);
<p/>
<nbsp/><nbsp/>CDPlayerSeek(ptr,
<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>NUM2INT(disc),
<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>NUM2INT(track),
<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>progress);
<nbsp/><nbsp/>return<nbsp/>Qnil;
}
<p/>
static<nbsp/>VALUE
cd_seekTime(VALUE<nbsp/>self)
{
<nbsp/><nbsp/>double<nbsp/>tm;
<nbsp/><nbsp/>CDJukebox<nbsp/>*ptr;
<nbsp/><nbsp/>Data_Get_Struct(self,<nbsp/>CDJukebox,<nbsp/>ptr);
<nbsp/><nbsp/>tm<nbsp/>=<nbsp/>CDPlayerAvgSeekTime(ptr);
<nbsp/><nbsp/>return<nbsp/>rb_float_new(tm);
}
<p/>
static<nbsp/>VALUE
cd_unit(VALUE<nbsp/>self)
{
<nbsp/><nbsp/>return<nbsp/>rb_iv_get(self,<nbsp/>"@unit");
}
<p/>
static<nbsp/>VALUE
cd_init(VALUE<nbsp/>self,<nbsp/>VALUE<nbsp/>unit)
{
<nbsp/><nbsp/>rb_iv_set(self,<nbsp/>"@unit",<nbsp/>unit);
<nbsp/><nbsp/>return<nbsp/>self;
}
<p/>
VALUE<nbsp/>cd_new(VALUE<nbsp/>class,<nbsp/>VALUE<nbsp/>unit)
{
<nbsp/><nbsp/>VALUE<nbsp/>argv[1];
<nbsp/><nbsp/>CDJukebox<nbsp/>*ptr<nbsp/>=<nbsp/>CDPlayerNew(NUM2INT(unit));
<nbsp/><nbsp/>VALUE<nbsp/>tdata<nbsp/>=<nbsp/>Data_Wrap_Struct(class,<nbsp/>0,<nbsp/>cd_free,<nbsp/>ptr);
<nbsp/><nbsp/>argv[0]<nbsp/>=<nbsp/>unit;
<nbsp/><nbsp/>rb_obj_call_init(tdata,<nbsp/>1,<nbsp/>argv);
<nbsp/><nbsp/>return<nbsp/>tdata;
}
<p/>
void<nbsp/>Init_CDJukebox()<nbsp/>{
<nbsp/><nbsp/>cCDPlayer<nbsp/>=<nbsp/>rb_define_class("CDPlayer",<nbsp/>rb_cObject);
<nbsp/><nbsp/>rb_define_singleton_method(cCDPlayer,<nbsp/>"new",<nbsp/>cd_new,<nbsp/>1);
<nbsp/><nbsp/>rb_define_method(cCDPlayer,<nbsp/>"initialize",<nbsp/>cd_init,<nbsp/>1);
<nbsp/><nbsp/>rb_define_method(cCDPlayer,<nbsp/>"seek",<nbsp/>cd_seek,<nbsp/>2);
<nbsp/><nbsp/>rb_define_method(cCDPlayer,<nbsp/>"seekTime",<nbsp/>cd_seekTime,<nbsp/>0);
<nbsp/><nbsp/>rb_define_method(cCDPlayer,<nbsp/>"unit",<nbsp/>cd_unit,<nbsp/>0);
}
</alltt>
</codefragment>
<p/>
Now we have the ability to control our jukebox from Ruby in a nice,
object-oriented manner:
<p/>
<codefragment>
<alltt><fullcode><![CDATA[  require "code/ext/CDJukebox"
  p = CDPlayer.new(1)
  puts "Unit is #{p.unit}"
  p.seek(3, 16) {|x| puts "#{x}% done" }
  puts "Avg. time was #{p.seekTime} seconds"
]]></fullcode>
require<nbsp/>"code/ext/CDJukebox"
p<nbsp/>=<nbsp/>CDPlayer.new(1)
puts<nbsp/>"Unit<nbsp/>is<nbsp/>#{p.unit}"
p.seek(3,<nbsp/>16)<nbsp/>{|x|<nbsp/>puts<nbsp/>"#{x}%<nbsp/>done"<nbsp/>}
puts<nbsp/>"Avg.<nbsp/>time<nbsp/>was<nbsp/>#{p.seekTime}<nbsp/>seconds"
</alltt>
</codefragment>
<em>produces:</em>
<codefragment><alltt>
Unit<nbsp/>is<nbsp/>1
26%<nbsp/>done
79%<nbsp/>done
100%<nbsp/>done
Avg.<nbsp/>time<nbsp/>was<nbsp/>1.2<nbsp/>seconds
</alltt>
</codefragment>
<p/>
This example demonstrates most of what we've talked about so far, with
one additional neat feature.  The vendor's library provided a callback
routine---a function pointer that is called every so often while the
hardware is grinding its way to the next disc.  We've set that up here
to run a code block passed as an argument to <tt>seek</tt>.  In the
<tt>progress</tt> function, we check to see if there is an iterator in the
current context and, if there is, run it
with the current percent done as an argument.
<section>Memory Allocation</section>
<p/>
You may sometimes need to allocate memory in an extension that
won't be used for object storage---perhaps you've got a giant bitmap
for a Bloom filter, or an image, or a whole bunch of little structures 
that Ruby doesn't use directly.
<p/>
In order to work correctly with the garbage collector, you should use
the following memory allocation routines.  These routines do a little
bit more work than the standard <tt>malloc</tt>.  For instance, if
<tt>ALLOC_N</tt> determines that it cannot allocate the desired amount of
memory, it will invoke the garbage collector to try to reclaim some
space. It will raise a
<exception>NoMemError</exception> if it can't or if the requested amount of memory is
invalid.
<p/>
  <table>
      <cdoctitle>Memory Allocation</cdoctitle>
      <cfunc name="ALLOC_N">
    <creturns><em>type *</em></creturns>
        <cparams><em>c-type</em>, n"</cparams>
        <cbody>    Allocates <em>n</em> <em>c-type</em> objects, where <em>c-type</em> is
    the literal name of the C type, not a variable of that type.</cbody>
      </cfunc>
  <cfunc name="ALLOC">
    <creturns><em>type *</em></creturns>
        <cparams><em>c-type</em>"</cparams>
        <cbody>    Allocates a <em>c-type</em> and casts the result to a pointer of
    that type.</cbody>
      </cfunc>
  <cfunc name="REALLOC_N">
    <creturns></creturns>
        <cparams><em>var</em>, <em>c-type</em>, n"</cparams>
        <cbody>    Reallocates <em>n</em> <em>c-type</em>s and assigns the result to <em>var</em>, 
    a pointer to a <em>c-type</em>.</cbody>
      </cfunc>
  <cfunc name="ALLOCA_N">
    <creturns><em>type *</em></creturns>
        <cparams><em>c-type</em>, n"</cparams>
        <cbody>    Allocates memory for <em>n</em> objects of <em>c-type</em> on the
    stack---this memory will be automatically freed when the function
    that invokes <tt>ALLOCA_N</tt> returns.</cbody>
      </cfunc>
<p/>
     </table>
<section>Creating an Extension</section>
<p/>
Having written the source code for an extension, we now need to compile
it so Ruby can use it. We can either do this as a shared
object, which is dynamically loaded at runtime, or statically link
the extension into the main Ruby interpreter itself.  The basic
procedure is the same:
<ul>
  <li> Create the C source code file(s) in a given directory.
  </li><li> Create <tt>extconf.rb</tt>.
  </li><li> Run <tt>extconf.rb</tt> to create a <tt>Makefile</tt> for the C files in 
    this directory.
  </li><li> Run <tt>make</tt>.
  </li><li> Run <tt>make install</tt>.
</li></ul>
<figure type="figure">Figure not available...</figure>
<p/>
<subsection>Creating a Makefile with extconf.rb</subsection>
<p/>
Figure 17.2 on page 182 shows the overall workflow when building an
extension.
The key to the whole process is the <tt>extconf.rb</tt>
program which you, as a developer, create. In <tt>extconf.rb</tt>, you
write a simple program that determines what features are available on
the user's system and where those features may be located. Executing
<tt>extconf.rb</tt> builds a customized
<tt>Makefile</tt>, tailored for both your application and the system on
which it's being compiled. When you run the <tt>make</tt> command against
this <tt>Makefile</tt>, your extension is built and (optionally) installed.
<p/>
The simplest <tt>extconf.rb</tt> may be just two lines long, and for many
extensions this is sufficient.
<p/>
<codefragment>
<alltt><fullcode><![CDATA[  require 'mkmf'
  create_makefile("Test")
]]></fullcode>
require<nbsp/>'mkmf'
create_makefile("Test")
</alltt>
</codefragment>
<p/>
The first line brings in the <classname>mkmf</classname> library module
(documented beginning on page 451). This contains all the
commands we'll be using. The second line creates a <tt>Makefile</tt> for an
extension called ``Test.'' (Note that ``Test'' is the name of the
extension; the makefile will always be called ``Makefile.'')
<tt>Test</tt> will be built from all the C source files in the
current directory.
<p/>
Let's say that we run this <tt>extconf.rb</tt> program in a directory
containing a single source file, <tt>main.c</tt>. The
result is a <tt>Makefile</tt> that will build our extension. On our system,
this contains the following commands.
<p/>
<codefragment>
<alltt><fullcode><![CDATA[  gcc -fPIC -I/usr/local/lib/ruby/1.6/i686-linux -g -O2  \
    -c main.c -o main.o
  gcc -shared -o Test.so main.o -lc 
]]></fullcode>
gcc<nbsp/>-fPIC<nbsp/>-I/usr/local/lib/ruby/1.6/i686-linux<nbsp/>-g<nbsp/>-O2<nbsp/><nbsp/>\
<nbsp/><nbsp/>-c<nbsp/>main.c<nbsp/>-o<nbsp/>main.o
gcc<nbsp/>-shared<nbsp/>-o<nbsp/>Test.so<nbsp/>main.o<nbsp/>-lc
</alltt>
</codefragment>
<p/>
The result of this compilation is <tt>Test.so</tt>, which may be
dynamically linked into Ruby at runtime with ``<tt>require</tt>''. See how 
the <tt>mkmf</tt> commands have located platform-specific libraries and
used compiler-specific options automatically. Pretty neat, eh?
<p/>
Although this basic program works for many simple extensions, you may
have to do some more work if your extension needs header files or
libraries that aren't included in the default compilation environment,
or if you conditionally compile code based on the presence of
libraries or functions.
<p/>
A common requirement is to specify nonstandard directories where
include files and libraries may be found. This is a two-step process.
First, your <tt>extconf.rb</tt> should contain one or more
<meth>dir_config</meth> commands.
This specifies a tag for a set of directories. Then, when you run the
<tt>extconf.rb</tt> program, you tell <tt>mkmf</tt> where the corresponding
physical directories are on the current system.
<p/>
If <tt>extconf.rb</tt> contains the line <tt>dir_config(</tt><em>name</em><tt>)</tt>,
then you give the location of the corresponding directories with the
command-line options:
<p/>
<dl>
  <dt><tt>--with-<em>name</em>-include=<em>directory</em></tt></dt><dd><br/>*
    Add  <em>directory</em>/<tt>include</tt> to the compile command.
  </dd><dt><tt>--with-<em>name</em>-lib=<em>directory</em></tt></dt><dd><br/>*
    Add <em>directory</em>/<tt>lib</tt> to the link command.
</dd></dl>
<p/>
If (as is common) your include and library directories are both
subdirectories of some other directory, and (as is also common) they're
called <tt>include</tt> and <tt>lib</tt>, you can take a shortcut:
<p/>
<dl>
<dt><tt>--with-<em>name</em>-dir=<em>directory</em></tt></dt><dd><br/>*
  Add <em>directory</em>/<tt>lib</tt> and <em>directory</em>/<tt>include</tt> to the link
  command and compile command, respectively.
</dd></dl>
<p/>
There's a twist here. As well as specifying all these <tt>--with</tt>
options when you run <tt>extconf.rb</tt>, you can also use the <tt>--with</tt>
options that were specified when Ruby was built for your machine. This
means you can find out the locations of libraries that are used by
Ruby itself.
<p/>
To make all this concrete, lets say you need to use libraries and
include files for the CD jukebox we're developing. Your
<tt>extconf.rb</tt> program might contain
<p/>
<codefragment>
<alltt><fullcode><![CDATA[  require 'mkmf'
  dir_config('cdjukebox')
  # .. more stuff
  create_makefile("CDJukeBox")
]]></fullcode>
require<nbsp/>'mkmf'
dir_config('cdjukebox')
#<nbsp/>..<nbsp/>more<nbsp/>stuff
create_makefile("CDJukeBox")
</alltt>
</codefragment>
<p/>
You'd then run <tt>extconf.rb</tt> with something like:
<p/>
<codefragment>
<alltt><fullcode><![CDATA[  % ruby extconf.rb --with-cdjukebox-dir=/usr/local/cdjb
]]></fullcode>
%<nbsp/>ruby<nbsp/>extconf.rb<nbsp/>--with-cdjukebox-dir=/usr/local/cdjb
</alltt>
</codefragment>
<p/>
The generated <tt>Makefile</tt> would assume that the libraries were in
<tt>/usr/local/cdjb/lib</tt> and the include files were in
<tt>/usr/local/cdjb/include</tt>.
<p/>
The <meth>dir_config</meth> command adds to the list of places to search
for libraries and include files. It does not, however, link the
libraries into your application. To do that, you'll need to use one
or more <meth>have_library</meth> or <meth>find_library</meth> commands.
<p/>
<meth>have_library</meth> looks for
a given entry point in a named library. If it finds the entry point,
it adds the library to the list of libraries to be used when linking
your extension.
<meth>find_library</meth> is
similar, but allows you to specify a list of directories to search for
the library.
<p/>
<codefragment>
<alltt><fullcode><![CDATA[  require 'mkmf'
  dir_config('cdjukebox')
  have_library('cdjb', 'CDPlayerNew')
  create_makefile("CDJukeBox")
]]></fullcode>
require<nbsp/>'mkmf'
dir_config('cdjukebox')
have_library('cdjb',<nbsp/>'CDPlayerNew')
create_makefile("CDJukeBox")
</alltt>
</codefragment>
<p/>
On some platforms, a popular library may be in one of several places.
The X Window system, for example, is notorious for living in different
directories on different systems.  The <tt>find_library</tt> command will
search a list of supplied directories to find the right one (this is
different from <tt>have_library</tt>, which uses only configuration
information for the search).  For example, to create a <tt>Makefile</tt>
that uses X Windows and a jpeg library, <tt>extconf.rb</tt> might contain
<p/>
<codefragment>
<alltt><fullcode><![CDATA[  require 'mkmf'

  if have_library("jpeg","jpeg_mem_init") and
     find_library("X11", "XOpenDisplay", "/usr/X11/lib",
                  "/usr/X11R6/lib", "/usr/openwin/lib")
  then
      create_makefile("XThing")
  else
      puts "No X/JPEG support available"
  end
]]></fullcode>
require<nbsp/>'mkmf'
<p/>
if<nbsp/>have_library("jpeg","jpeg_mem_init")<nbsp/>and
<nbsp/><nbsp/><nbsp/>find_library("X11",<nbsp/>"XOpenDisplay",<nbsp/>"/usr/X11/lib",
<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>"/usr/X11R6/lib",<nbsp/>"/usr/openwin/lib")
then
<nbsp/><nbsp/><nbsp/><nbsp/>create_makefile("XThing")
else
<nbsp/><nbsp/><nbsp/><nbsp/>puts<nbsp/>"No<nbsp/>X/JPEG<nbsp/>support<nbsp/>available"
end
</alltt>
</codefragment>
<p/>
We've added some additional functionality to this program. All of the
<tt>mkmf</tt> commands return <const>false</const> if they fail. This means that
we can write an <tt>extconf.rb</tt> that generates a <tt>Makefile</tt> only if
everything it needs is present.  The Ruby distribution does
this so that it will try to compile only those extensions that are supported
on your system.
<p/>
You also may want your extension code to be able to configure the
features it uses depending on the target environment. For example, our
CD jukebox may be able to use a high-performance MP3 decoder if the
end user has one installed. We can check by looking for its header
file.
<p/>
<codefragment>
<alltt><fullcode><![CDATA[  require 'mkmf'
  dir_config('cdjukebox')
  have_library('cdjb', 'CDPlayerNew')
  have_header('hp_mp3.h')
  create_makefile("CDJukeBox")
]]></fullcode>
require<nbsp/>'mkmf'
dir_config('cdjukebox')
have_library('cdjb',<nbsp/>'CDPlayerNew')
have_header('hp_mp3.h')
create_makefile("CDJukeBox")
</alltt>
</codefragment>
<p/>
We can also check to see if the target environment has a particular
function in any of the libraries we'll be using. For example, the
<meth>setpriority</meth> call would be useful but isn't always
available. We can check for it with:
<p/>
<codefragment>
<alltt><fullcode><![CDATA[  require 'mkmf'
  dir_config('cdjukebox')
  have_func('setpriority')
  create_makefile("CDJukeBox")
]]></fullcode>
require<nbsp/>'mkmf'
dir_config('cdjukebox')
have_func('setpriority')
create_makefile("CDJukeBox")
</alltt>
</codefragment>
<p/>
Both <meth>have_header</meth> and <meth>have_func</meth> define
preprocessor constants if they find their targets. The names are
formed by converting the target name to uppercase and prepending
``HAVE_''. Your C code can take advantage of this using constructs
such as:
<p/>
<codefragment>
<alltt><fullcode><![CDATA[  #if defined(HAVE_HP_MP3_H)
  #  include <hp_mp3.h>
  #endif
  
  #if defined(HAVE_SETPRIORITY)
    err = setpriority(PRIOR_PROCESS, 0, -10)
  #endif
]]></fullcode>
#if<nbsp/>defined(HAVE_HP_MP3_H)
#<nbsp/><nbsp/>include<nbsp/>&lt;hp_mp3.h&gt;
#endif
<p/>
#if<nbsp/>defined(HAVE_SETPRIORITY)
<nbsp/><nbsp/>err<nbsp/>=<nbsp/>setpriority(PRIOR_PROCESS,<nbsp/>0,<nbsp/>-10)
#endif
</alltt>
</codefragment>
<p/>
If you have special requirements that can't be met with all
these <tt>mkmf</tt> commands, your program can directly add to the global
variables <tt>$CFLAGS</tt> and <tt>$LFLAGS</tt>, which are passed to the
compiler and linker, respectively.
<subsection>Static Linking</subsection>
<p/>
Finally, if your system doesn't support dynamic linking, or if you
have an extension module that you want to have statically linked into
Ruby itself, edit the file <tt>ext/Setup</tt> in
the distribution and add your directory to the list of extensions in
the file, then rebuild Ruby.
The extensions listed in <tt>Setup</tt> will be
statically linked into the Ruby executable.  If you want to disable
any dynamic linking, and link all extensions statically, edit
<tt>ext/Setup</tt> to contain the following option.
<p/>
<codefragment>
<alltt><fullcode><![CDATA[  option nodynamic
]]></fullcode>
option<nbsp/>nodynamic
</alltt>
</codefragment>
<section>Embedding a Ruby Interpreter</section>
<p/>
In addition to extending Ruby by adding C code, you can also turn the
problem around and embed Ruby itself within your application.  
Here's an example.
<p/>
<codefragment>
<alltt><fullcode><![CDATA[#include "ruby.h"

main() {
  /* ... our own application stuff ... */
  ruby_init();
  ruby_script("embedded");
  rb_load_file("start.rb");
  while (1) {
    if (need_to_do_ruby) {
      ruby_run();
    }
    /* ... run our app stuff */
  }
}
]]></fullcode>
#include<nbsp/>"ruby.h"
<p/>
main()<nbsp/>{
<nbsp/><nbsp/>/*<nbsp/>...<nbsp/>our<nbsp/>own<nbsp/>application<nbsp/>stuff<nbsp/>...<nbsp/>*/
<nbsp/><nbsp/>ruby_init();
<nbsp/><nbsp/>ruby_script("embedded");
<nbsp/><nbsp/>rb_load_file("start.rb");
<nbsp/><nbsp/>while<nbsp/>(1)<nbsp/>{
<nbsp/><nbsp/><nbsp/><nbsp/>if<nbsp/>(need_to_do_ruby)<nbsp/>{
<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>ruby_run();
<nbsp/><nbsp/><nbsp/><nbsp/>}
<nbsp/><nbsp/><nbsp/><nbsp/>/*<nbsp/>...<nbsp/>run<nbsp/>our<nbsp/>app<nbsp/>stuff<nbsp/>*/
<nbsp/><nbsp/>}
}
</alltt>
</codefragment>
<p/>
To initialize the Ruby interpreter, you need to call
<tt>ruby_init()</tt>. But on some platforms, you may need to take special
steps before that:
<p/>
<codefragment>
<alltt><fullcode><![CDATA[  #if defined(NT)
    NtInitialize(&argc, &argv);
  #endif
  #if defined(__MACOS__) && defined(__MWERKS__)
    argc = ccommand(&argv);
  #endif
]]></fullcode>
#if<nbsp/>defined(NT)
<nbsp/><nbsp/>NtInitialize(&amp;argc,<nbsp/>&amp;argv);
#endif
#if<nbsp/>defined(__MACOS__)<nbsp/>&amp;&amp;<nbsp/>defined(__MWERKS__)
<nbsp/><nbsp/>argc<nbsp/>=<nbsp/>ccommand(&amp;argv);
#endif
</alltt>
</codefragment>
<p/>
See <tt>main.c</tt> in the Ruby distribution for any other special defines
or setup needed for your platform.
<p/>
  <table>
      <cdoctitle>Embedded Ruby API</cdoctitle>
      <cfunc name="ruby_init">
    <creturns>void</creturns>
        <cparams>"</cparams>
        <cbody>    Sets up and initializes the interpreter.  This function should be
    called before any other Ruby-related functions.
  </cbody>
      </cfunc>
  <cfunc name="ruby_options">
    <creturns>void</creturns>
        <cparams>int<nbsp/>argc, char<nbsp/>**argv"</cparams>
        <cbody>    Gives the Ruby interpreter the command-line options.
  </cbody>
      </cfunc>
  <cfunc name="ruby_script">
    <creturns>void</creturns>
        <cparams>char<nbsp/>*name"</cparams>
        <cbody>    Sets the name of the Ruby script (and <kw>$0</kw>) to <em>name</em>.
  </cbody>
      </cfunc>
  <cfunc name="rb_load_file">
    <creturns>void</creturns>
        <cparams>char<nbsp/>*file"</cparams>
        <cbody>      Loads the given file into the interpreter.
  </cbody>
      </cfunc>
  <cfunc name="ruby_run">
    <creturns>void</creturns>
        <cparams>"</cparams>
        <cbody>      Runs the interpreter.
  </cbody>
      </cfunc>
<p/>
     </table>
<p/>
You need to take some special care with exception handling; any Ruby
calls you make at this top level should be protected to catch
exceptions and handle them cleanly.  <tt>rb_protect</tt>, <tt>rb_rescue</tt>, and related
functions are documented on page 192.
<p/>
For an example of embedding a Ruby interpreter within another program, 
see also <tt>eruby</tt>, which is described beginning on page 147.
<section>Bridging Ruby to Other Languages</section>
<p/>
So far, we've discussed extending Ruby by adding routines written in C.
However, you can write extensions in just about any language, as long
as you can bridge the two languages with C. Almost anything is
possible, including awkward marriages of Ruby and C++, Ruby and Java,
and so on.
<p/>
But you may be able to accomplish the same thing without resorting to C 
code.  For example, you could bridge to other languages using
middleware such as CORBA or COM.  See the section on Windows automation
beginning on page 164 for more details.
<section>Ruby C Language API</section>
<p/>
Last, but by no means least, here are several C-level functions 
that you may find useful when writing an extension.
<p/>
Some functions require an <tt>ID</tt>: you can
obtain an <tt>ID</tt> for a string by using <tt>rb_intern</tt> and
reconstruct the name from an <tt>ID</tt> by using <tt>rb_id2name</tt>.
<p/>
As most of these C functions have Ruby equivalents that are already
described in detail elsewhere in this book, the descriptions here will
be brief.
<p/>
Also note that the following listing is not complete. There are many more
functions available---too many to document them all, as it turns out.
If you need a method that you can't find here, check ``<tt>ruby.h</tt>'' or
``<tt>intern.h</tt>'' for likely candidates.  Also, at or near the bottom
of each source file is a set of method definitions that describe the
binding from Ruby methods to C functions.  You may be able to call the 
C function directly, or search for a wrapper function that calls the
function you are looking for.  The following list, based on the list
in <tt>README.EXT</tt>, shows the main source
files in the interpreter.
<p/>
<dl>
  <dt>Ruby Language Core</dt><dd><br/>class.c error.c eval.c gc.c object.c parse.y variable.c
  </dd><dt>Utility Functions</dt><dd><br/>dln.c regex.c st.c util.c
  </dd><dt>Ruby Interpreter</dt><dd><br/>dmyext.c inits.c keywords main.c ruby.c version.c
  </dd><dt>Base Library</dt><dd><br/>array.c bignum.c compar.c dir.c enum.c file.c hash.c io.c marshal.c math.c numeric.c pack.c prec.c process.c random.c range.c re.c signal.c sprintf.c string.c struct.c time.c
</dd></dl>
<p/>
  <table>
      <cdoctitle>Defining Objects</cdoctitle>
      <cfunc name="rb_define_class">
    <creturns>VALUE</creturns>
        <cparams>char<nbsp/>*name, VALUE<nbsp/>superclass"</cparams>
        <cbody>    Defines a new class at the top level with the given <em>name</em> and
    <em>superclass</em> (for class <tt>Object</tt>, use <tt>rb_cObject</tt>).
  </cbody>
      </cfunc>
  <cfunc name="rb_define_module">
    <creturns>VALUE</creturns>
        <cparams>char<nbsp/>*name"</cparams>
        <cbody>    Defines a new module at the top level with the given <em>name</em>.
  </cbody>
      </cfunc>
  <cfunc name="rb_define_class_under">
    <creturns>VALUE</creturns>
        <cparams>VALUE<nbsp/>under, char<nbsp/>*name, 
    VALUE<nbsp/>superclass"</cparams>
        <cbody>    Defines a nested class under the class or module <em>under</em>.
  </cbody>
      </cfunc>
  <cfunc name="rb_define_module_under">
    <creturns>VALUE</creturns>
        <cparams>VALUE<nbsp/>under, char<nbsp/>*name"</cparams>
        <cbody>    Defines a nested module under the class or module <em>under</em>.
  </cbody>
      </cfunc>
  <cfunc name="rb_include_module">
    <creturns>void</creturns>
        <cparams>VALUE<nbsp/>parent, VALUE<nbsp/>module"</cparams>
        <cbody>    Includes the given <em>module</em> into the class or module
    <em>parent</em>.
  </cbody>
      </cfunc>
  <cfunc name="rb_extend_object">
    <creturns>void</creturns>
        <cparams>VALUE<nbsp/>obj, VALUE<nbsp/>module"</cparams>
        <cbody>    Extends <em>obj</em> with <em>module</em>.
  </cbody>
      </cfunc>
  <cfunc name="rb_require">
    <creturns>VALUE</creturns>
        <cparams>const<nbsp/>char<nbsp/>*name"</cparams>
        <cbody>    Equivalent to ``<kw>require</kw> <em>name</em>.''
    Returns <tt>Qtrue</tt> or <tt>Qfalse</tt>.
  </cbody>
      </cfunc>
<p/>
     </table>
<p/>
  In some of the function definitions that follow, the parameter
  <em>argc</em> specifies how many arguments a Ruby method takes.  It
  may have the following values.
<p/>
<table>
<th>
  <td><b><em>argc</em></b></td>
  <td><b>Function prototype</b></td>
</th>
<tr>
  <td>0..17</td>
  <td><tt>VALUE func(VALUE self, VALUE arg...)</tt></td>
</tr>
<tr>
  <td></td>
  <td>The C function will be called with this many actual arguments.</td>
</tr>
<tr>
  <td>-1</td>
  <td><tt>VALUE func(int argc, VALUE *argv, VALUE self)</tt></td>
</tr>
<tr>
  <td></td>
  <td>The C function will be given a variable number of arguments passed
  as a C array.</td>
</tr>
<tr>
  <td>-2</td>
  <td><tt>VALUE func(VALUE self, VALUE args)</tt></td>
</tr>
<tr>
  <td></td>
  <td>The C function will be given a variable number of arguments
    passed as a Ruby array.</td>
</tr>
<bottomrule/></table>
<p/>
In a function that has been given a variable number of arguments,
you can use the C function <tt>rb_scan_args</tt> to sort things out (see below).
<p/>
  <table>
      <cdoctitle>Defining Methods</cdoctitle>
      <cfunc name="rb_define_method">
    <creturns>void</creturns>
        <cparams>VALUE<nbsp/>classmod, char<nbsp/>*name,
    VALUE(*func)(), int<nbsp/>argc"</cparams>
        <cbody>    Defines an instance method in the class or module <em>classmod</em> with the given <em>name</em>, implemented
  by the C function <em>func</em> and taking <em>argc</em> arguments.
  </cbody>
      </cfunc>
  <cfunc name="rb_define_module_function">
    <creturns>void</creturns>
        <cparams>VALUE<nbsp/>classmod, char<nbsp/>*name,
    VALUE(*func)(), int<nbsp/>argc)"</cparams>
        <cbody>    Defines a method in class <em>classmod</em> with the given <em>name</em>, implemented
  by the C function <em>func</em> and taking <em>argc</em> arguments.
  </cbody>
      </cfunc>
  <cfunc name="rb_define_global_function">
    <creturns>void</creturns>
        <cparams>char<nbsp/>*name, VALUE(*func)(),
    int<nbsp/>argc"</cparams>
        <cbody>    Defines a global function (a private method of <modulename>Kernel</modulename>) with the given <em>name</em>, implemented
  by the C function <em>func</em> and taking <em>argc</em> arguments.
  </cbody>
      </cfunc>
  <cfunc name="rb_define_singleton_method">
    <creturns>void</creturns>
        <cparams>VALUE<nbsp/>classmod, char<nbsp/>*name,
    VALUE(*func)(), int<nbsp/>argc"</cparams>
        <cbody>    Defines a singleton method in class <em>classmod</em> with the given <em>name</em>, implemented
  by the C function <em>func</em> and taking <em>argc</em> arguments.
  </cbody>
      </cfunc>
  <cfunc name="rb_scan_args">
    <creturns>int</creturns>
        <cparams>int<nbsp/>argcount, VALUE<nbsp/>*argv, char<nbsp/>*fmt, ..."</cparams>
        <cbody>
    Scans the argument list and assigns to variables similar to
    <tt>scanf</tt>: <em>fmt</em> is a string containing zero, one, or two
    digits followed by some flag characters.
    The first digit indicates the count of
    mandatory arguments; the second is the count of optional
    arguments. A ``*'' means to pack the rest of the arguments into a
    Ruby array. A ``&amp;'' means that an attached code block will be
    taken and assigned to the given variable (if no code block was
    given, <tt>Qnil</tt> will be assigned).
    After the <em>fmt</em> string, pointers to <tt>VALUE</tt>
    are given (as with <tt>scanf</tt>) to which the arguments are
    assigned.
<p/>
<codefragment>
<alltt><fullcode><![CDATA[VALUE name, one, two, rest; 
rb_scan_args(argc, argv, "12", &name, &one, &two);
rb_scan_args(argc, argv, "1*", &name, &rest);
]]></fullcode>
VALUE<nbsp/>name,<nbsp/>one,<nbsp/>two,<nbsp/>rest;
rb_scan_args(argc,<nbsp/>argv,<nbsp/>"12",<nbsp/>&amp;name,<nbsp/>&amp;one,<nbsp/>&amp;two);
rb_scan_args(argc,<nbsp/>argv,<nbsp/>"1*",<nbsp/>&amp;name,<nbsp/>&amp;rest);
</alltt>
</codefragment>
  </cbody>
      </cfunc>
<p/>
  <cfunc name="rb_undef_method">
    <creturns>void</creturns>
        <cparams>VALUE<nbsp/>classmod, const<nbsp/>char<nbsp/>*name"</cparams>
        <cbody>    Undefines the given method <em>name</em> in the given <em>classmod</em>
    class or module.
  </cbody>
      </cfunc>
  <cfunc name="rb_define_alias">
    <creturns>void</creturns>
        <cparams>VALUE<nbsp/>classmod, const<nbsp/>char<nbsp/>*newname,
    const<nbsp/>char<nbsp/>*oldname"</cparams>
        <cbody>    Defines an alias for <em>oldname</em> in class or module
    <em>classmod</em>.
  </cbody>
      </cfunc>
<p/>
     </table>
<p/>
  <table>
      <cdoctitle>Defining Variables and Constants</cdoctitle>
      <cfunc name="rb_define_const">
    <creturns>void</creturns>
        <cparams>VALUE<nbsp/>classmod, char<nbsp/>*name, VALUE<nbsp/>value"</cparams>
        <cbody>    Defines a constant in the class or module <em>classmod</em>, with the
    given <em>name</em> and <em>value</em>.
  </cbody>
      </cfunc>
  <cfunc name="rb_define_global_const">
    <creturns>void</creturns>
        <cparams>char<nbsp/>*name, VALUE<nbsp/>value"</cparams>
        <cbody>    Defines a global constant with the
    given <em>name</em> and <em>value</em>.
  </cbody>
      </cfunc>
<p/>
  <cfunc name="rb_define_variable">
    <creturns>void</creturns>
        <cparams>const<nbsp/>char<nbsp/>*name, VALUE<nbsp/>*object"</cparams>
        <cbody>    Exports the address of the given <em>object</em> that was created
    in C to the Ruby namespace as <em>name</em>.  From Ruby, this will
    be a global variable, so <em>name</em> should start with a leading
    dollar sign.  Be sure to honor Ruby's rules for allowed variable
    names; illegally named variables will not be accessible from Ruby.
    </cbody>
      </cfunc>
<p/>
  <cfunc name="rb_define_class_variable">
    <creturns>void</creturns>
        <cparams>VALUE<nbsp/>class, const<nbsp/>char<nbsp/>*name,
    VALUE<nbsp/>val"</cparams>
        <cbody>    Defines a class variable <em>name</em> 
    (which must be specified with a ``<tt>@@</tt>'' prefix) in the given 
    <em>class</em>, initialized to <em>value</em>.
  </cbody>
      </cfunc>
<p/>
  <cfunc name="rb_define_virtual_variable">
    <creturns>void</creturns>
        <cparams>const<nbsp/>char<nbsp/>*name,
    VALUE(*getter)(), void(*setter)()"</cparams>
        <cbody>
    Exports a virtual variable to Ruby namespace as the global
    $<em>name</em>. No
    actual storage exists for the variable; attempts to get and set
    the value will call the given functions with the prototypes:
<p/>
<codefragment>
<alltt><fullcode><![CDATA[VALUE getter(ID id, VALUE *data,
             struct global_entry *entry);
void setter(VALUE value, ID id, VALUE *data,
            struct global_entry *entry);
]]></fullcode>
VALUE<nbsp/>getter(ID<nbsp/>id,<nbsp/>VALUE<nbsp/>*data,
<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>struct<nbsp/>global_entry<nbsp/>*entry);
void<nbsp/>setter(VALUE<nbsp/>value,<nbsp/>ID<nbsp/>id,<nbsp/>VALUE<nbsp/>*data,
<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>struct<nbsp/>global_entry<nbsp/>*entry);
</alltt>
</codefragment>
<p/>
    You will likely not need to use the <em>entry</em>  parameter
    and can safely omit it from your function
    declarations.
  </cbody>
      </cfunc>
<p/>
  <cfunc name="rb_define_hooked_variable">
    <creturns>void</creturns>
        <cparams>const<nbsp/>char<nbsp/>*name,
    VALUE<nbsp/>*variable, VALUE(*getter)(), void(*setter)()"</cparams>
        <cbody>    Defines functions to be called when reading or writing to
    <em>variable</em>. See also <tt>rb_define_virtual_variable</tt>.
  </cbody>
      </cfunc>
  <cfunc name="rb_define_readonly_variable">
    <creturns>void</creturns>
        <cparams>const<nbsp/>char<nbsp/>*name,
    VALUE<nbsp/>*value"</cparams>
        <cbody>    Same as <kw>rb_define_variable</kw>, but read-only from Ruby.
  </cbody>
      </cfunc>
  <cfunc name="rb_define_attr">
    <creturns>void</creturns>
        <cparams>VALUE<nbsp/>variable, const<nbsp/>char<nbsp/>*name,
    int<nbsp/>read, int<nbsp/>write"</cparams>
        <cbody>    Creates accessor methods for the given <em>variable</em>, with the given
    <em>name</em>.  If <em>read</em> is nonzero, create a read method; if
    <em>write</em> is nonzero, create a write method.
  </cbody>
      </cfunc>
  <cfunc name="rb_global_variable">
    <creturns>void</creturns>
        <cparams>VALUE<nbsp/>*obj"</cparams>
        <cbody>    Registers the given address with the garbage collector.</cbody>
      </cfunc>
<p/>
     </table>
<p/>
  <table>
      <cdoctitle>Calling Methods</cdoctitle>
      <cfunc name="rb_funcall">
    <creturns>VALUE</creturns>
        <cparams>VALUE<nbsp/>recv, ID<nbsp/>id, int<nbsp/>argc, ..."</cparams>
        <cbody>    Invokes the method given by <em>id</em> in the object <em>recv</em>
    with the given number of arguments <em>argc</em> and the arguments
    themselves (possibly none).
  </cbody>
      </cfunc>
  <cfunc name="rb_funcall2">
    <creturns>VALUE</creturns>
        <cparams>VALUE<nbsp/>recv, ID<nbsp/>id, int<nbsp/>argc, VALUE<nbsp/>*args"</cparams>
        <cbody>    Invokes the method given by <em>id</em> in the object <em>recv</em>
    with the given number of arguments <em>argc</em> and the arguments
    themselves given in the C array <em>args</em>.
  </cbody>
      </cfunc>
  <cfunc name="rb_funcall3">
    <creturns>VALUE</creturns>
        <cparams>VALUE<nbsp/>recv, ID<nbsp/>id, int<nbsp/>argc, VALUE<nbsp/>*args"</cparams>
        <cbody>    Same as <tt>rb_funcall2</tt>, but will not call private methods.
  </cbody>
      </cfunc>
<p/>
  <cfunc name="rb_apply">
    <creturns>VALUE</creturns>
        <cparams>VALUE<nbsp/>recv, ID<nbsp/>name, int<nbsp/>argc, VALUE<nbsp/>args"</cparams>
        <cbody>    Invokes the method given by <em>id</em> in the object <em>recv</em>
    with the given number of arguments <em>argc</em> and the arguments
    themselves given in the Ruby <classname>Array</classname> <em>args</em>.
  </cbody>
      </cfunc>
  <cfunc name="rb_intern">
    <creturns>ID</creturns>
        <cparams>char<nbsp/>*name"</cparams>
        <cbody>    Returns an <kw>ID</kw> for a given <em>name</em>. If the name does not
    exist, a symbol table entry will be created for it.
  </cbody>
      </cfunc>
  <cfunc name="rb_id2name">
    <creturns>char *</creturns>
        <cparams>ID<nbsp/>id"</cparams>
        <cbody>    Returns a name for the given <em>id</em>.
  </cbody>
      </cfunc>
  <cfunc name="rb_call_super">
    <creturns>VALUE</creturns>
        <cparams>int<nbsp/>argc, VALUE<nbsp/>*args"</cparams>
        <cbody>    Calls the current method in the superclass of the current object.
  </cbody>
      </cfunc>
<p/>
     </table>
<p/>
  <table>
      <cdoctitle>Exceptions</cdoctitle>
      <cfunc name="rb_raise">
    <creturns>void</creturns>
        <cparams>VALUE exception, const<nbsp/>char<nbsp/>*fmt, ..."</cparams>
        <cbody>    Raises an <em>exception</em>.  
    The given string <em>fmt</em> and remaining arguments 
  are interpreted as with <kw>printf</kw>.
  </cbody>
      </cfunc>
  <cfunc name="rb_fatal">
    <creturns>void</creturns>
        <cparams>const<nbsp/>char<nbsp/>*fmt, ..."</cparams>
        <cbody>    Raises a <exception>Fatal</exception> exception, terminating the process. No
    rescue blocks are called, but ensure blocks will be called.
    The given string <em>fmt</em> and remaining arguments 
  are interpreted as with <kw>printf</kw>.
  </cbody>
      </cfunc>
  <cfunc name="rb_bug">
    <creturns>void</creturns>
        <cparams>const<nbsp/>char<nbsp/>*fmt, ..."</cparams>
        <cbody>    Terminates the process immediately---no handlers of any sort will
    be called.  
    The given string <em>fmt</em> and remaining arguments 
  are interpreted as with <kw>printf</kw>.
    You should call this function only if a fatal bug
    has been exposed.  You don't write fatal bugs, do you?
  </cbody>
      </cfunc>
  <cfunc name="rb_sys_fail">
    <creturns>void</creturns>
        <cparams>const<nbsp/>char<nbsp/>*msg"</cparams>
        <cbody>    Raises a platform-specific exception corresponding to the last
    known system error, with the given <em>msg</em>.
  </cbody>
      </cfunc>
  <cfunc name="rb_rescue">
    <creturns>VALUE</creturns>
        <cparams>VALUE<nbsp/>(*body)(), VALUE<nbsp/>args,
    VALUE(*rescue)(), VALUE<nbsp/>rargs"</cparams>
        <cbody>    Executes <em>body</em> with the given <em>args</em>.  If a
    <exception>StandardError</exception> exception is raised,
    then execute <em>rescue</em> with the given <em>rargs</em>.
  </cbody>
      </cfunc>
  <cfunc name="rb_ensure">
    <creturns>VALUE</creturns>
        <cparams>VALUE(*body)(), VALUE<nbsp/>args,
    VALUE(*ensure)(), VALUE<nbsp/>eargs"</cparams>
        <cbody>    Executes <em>body</em> with the given <em>args</em>.  Whether or not an 
    exception is raised, execute <em>ensure</em> with the given <em>rargs</em>
    after <em>body</em> has completed.
  </cbody>
      </cfunc>
  <cfunc name="rb_protect">
    <creturns>VALUE</creturns>
        <cparams>VALUE<nbsp/>(*body)(), VALUE<nbsp/>args,
    int<nbsp/>*result"</cparams>
        <cbody>    Executes <em>body</em> with the given
    <em>args</em> and returns nonzero in <em>result</em> if any exception
    was raised.
  </cbody>
      </cfunc>
  <cfunc name="rb_notimplement">
    <creturns>void</creturns>
        <cparams>"</cparams>
        <cbody>    Raises a <exception>NotImpError</exception> exception to indicate that the enclosed
    function is not implemented yet, or not available on this
    platform.
  </cbody>
      </cfunc>
  <cfunc name="rb_exit">
    <creturns>void</creturns>
        <cparams>int<nbsp/>status"</cparams>
        <cbody>    Exits Ruby with the given <em>status</em>. Raises a <exception>SystemExit</exception>
    exception and calls registered exit functions and
    finalizers.
  </cbody>
      </cfunc>
  <cfunc name="rb_warn">
    <creturns>void</creturns>
        <cparams>const<nbsp/>char<nbsp/>*fmt, ..."</cparams>
        <cbody>    Unconditionally issues a warning message to standard error.
    The given string <em>fmt</em> and remaining arguments 
  are interpreted as with <kw>printf</kw>.
  </cbody>
      </cfunc>
  <cfunc name="rb_warning">
    <creturns>void</creturns>
        <cparams>const<nbsp/>char<nbsp/>*fmt, ..."</cparams>
        <cbody>    Conditionally issues a warning message to standard error if Ruby
    was invoked with the <kw>-w</kw> flag.
    The given string <em>fmt</em> and remaining arguments 
  are interpreted as with <kw>printf</kw>.
  </cbody>
      </cfunc>
<p/>
     </table>
<p/>
  <table>
      <cdoctitle>Iterators</cdoctitle>
      <cfunc name="rb_iter_break">
    <creturns>void</creturns>
        <cparams>"</cparams>
        <cbody>    Breaks out of the enclosing iterator block.
  </cbody>
      </cfunc>
  <cfunc name="rb_each">
    <creturns>VALUE</creturns>
        <cparams>VALUE<nbsp/>obj"</cparams>
        <cbody>    Invokes the <kw>each</kw> method of the given <em>obj</em>.
  </cbody>
      </cfunc>
  <cfunc name="rb_yield">
    <creturns>VALUE</creturns>
        <cparams>VALUE<nbsp/>arg"</cparams>
        <cbody>    Transfers execution to the iterator block in the current context,
    passing <em>arg</em> as an argument. Multiple values may be passed
    in an array.
  </cbody>
      </cfunc>
  <cfunc name="rb_block_given_p">
    <creturns>int</creturns>
        <cparams>"</cparams>
        <cbody>    Returns true if <tt>yield</tt> would execute a block in the current
    context---that is, if a code block was passed to the current method 
    and is available to be called.
  </cbody>
      </cfunc>
  <cfunc name="rb_iterate">
    <creturns>VALUE</creturns>
        <cparams>VALUE<nbsp/>(*method)(), VALUE<nbsp/>args,
    VALUE<nbsp/>(*block)(), VALUE<nbsp/>arg2"</cparams>
        <cbody>    Invokes <em>method</em> with argument <em>args</em> and block
    <em>block</em>.  A <kw>yield</kw> from that method will invoke
    <em>block</em> with the argument given to <kw>yield</kw>, and a second
    argument <em>arg2</em>.
  </cbody>
      </cfunc>
  <cfunc name="rb_catch">
    <creturns>VALUE</creturns>
        <cparams>const<nbsp/>char<nbsp/>*tag, VALUE<nbsp/>(*proc)(), VALUE<nbsp/>value"</cparams>
        <cbody>    Equivalent to Ruby <tt>catch</tt>.
  </cbody>
      </cfunc>
  <cfunc name="rb_throw">
    <creturns>void</creturns>
        <cparams>const<nbsp/>char<nbsp/>*tag , VALUE<nbsp/>value"</cparams>
        <cbody>    Equivalent to Ruby <tt>throw</tt>.
  </cbody>
      </cfunc>
<p/>
     </table>
<p/>
  <table>
      <cdoctitle>Accessing Variables</cdoctitle>
      <cfunc name="rb_iv_get">
    <creturns>VALUE</creturns>
        <cparams>VALUE<nbsp/>obj, char<nbsp/>*name"</cparams>
        <cbody>    Returns the instance variable <em>name</em> (which must be specified
    with a ``<tt>@</tt>'' prefix) from the given <em>obj</em>.
  </cbody>
      </cfunc>
  <cfunc name="rb_ivar_get">
    <creturns>VALUE</creturns>
        <cparams>VALUE<nbsp/>obj, ID<nbsp/>name"</cparams>
        <cbody>    Returns the instance variable <em>name</em> from the given <em>obj</em>.
  </cbody>
      </cfunc>
  <cfunc name="rb_iv_set">
    <creturns>VALUE</creturns>
        <cparams>VALUE<nbsp/>obj, char<nbsp/>*name, VALUE<nbsp/>value"</cparams>
        <cbody>    Sets the value of the instance variable <em>name</em> (which must be
    specified with a ``<tt>@</tt>'' prefix) in the given <em>obj</em> to
    <em>value</em>.  Returns <em>value</em>.  
  </cbody>
      </cfunc>
  <cfunc name="rb_ivar_set">
    <creturns>VALUE</creturns>
        <cparams>VALUE<nbsp/>obj, ID<nbsp/>name, VALUE<nbsp/>value"</cparams>
        <cbody>    Sets the value of the instance variable <em>name</em> 
    in the given <em>obj</em> to <em>value</em>.  Returns
    <em>value</em>.
  </cbody>
      </cfunc>
  <cfunc name="rb_gv_set">
    <creturns>VALUE</creturns>
        <cparams>const<nbsp/>char<nbsp/>*name, VALUE<nbsp/>value"</cparams>
        <cbody>    Sets the global variable <em>name</em> (the ``<tt>$</tt>'' prefix is
    optional) to <em>value</em>. Returns <em>value</em>.  
  </cbody>
      </cfunc>
  <cfunc name="rb_gv_get">
    <creturns>VALUE</creturns>
        <cparams>const<nbsp/>char<nbsp/>*name"</cparams>
        <cbody>    Returns the global variable <em>name</em> (the ``<tt>$</tt>'' prefix is
    optional).  
  </cbody>
      </cfunc>
  <cfunc name="rb_cvar_set">
    <creturns>void</creturns>
        <cparams>VALUE<nbsp/>class, ID<nbsp/>name, VALUE<nbsp/>val"</cparams>
        <cbody>    Sets the class variable <em>name</em> in the given 
    <em>class</em> to <em>value</em>.
  </cbody>
      </cfunc>
<p/>
  <cfunc name="rb_cvar_get">
    <creturns>VALUE</creturns>
        <cparams>VALUE<nbsp/>class, ID<nbsp/>name"</cparams>
        <cbody>    Returns the class variable <em>name</em> 
    from the given <em>class</em>.
  </cbody>
      </cfunc>
<p/>
  <cfunc name="rb_cvar_defined">
    <creturns>int</creturns>
        <cparams>VALUE<nbsp/>class, ID<nbsp/>name"</cparams>
        <cbody>    Returns <tt>Qtrue</tt> if the given class variable
    <em>name</em> has been defined for <em>class</em>; otherwise, returns 
    <tt>Qfalse</tt>.
  </cbody>
      </cfunc>
<p/>
  <cfunc name="rb_cv_set">
    <creturns>void</creturns>
        <cparams>VALUE<nbsp/>class, const<nbsp/>char<nbsp/>*name, VALUE<nbsp/>val"</cparams>
        <cbody>    Sets the class variable <em>name</em> 
    (which must be specified with a ``<tt>@@</tt>'' prefix) in the given 
    <em>class</em> to <em>value</em>.
  </cbody>
      </cfunc>
<p/>
  <cfunc name="rb_cv_get">
    <creturns>VALUE</creturns>
        <cparams>VALUE<nbsp/>class, const<nbsp/>char<nbsp/>*name"</cparams>
        <cbody>    Returns the class variable <em>name</em> (which must be specified
    with a ``<tt>@@</tt>'' prefix) from the given <em>class</em>.
  </cbody>
      </cfunc>
<p/>
     </table>
<p/>
  <table>
      <cdoctitle>Object Status</cdoctitle>
      <cfunc name="OBJ_TAINT">
    <creturns></creturns>
        <cparams>VALUE<nbsp/>obj"</cparams>
        <cbody>    Marks the given <em>obj</em> as tainted.
  </cbody>
      </cfunc>
  <cfunc name="OBJ_TAINTED">
    <creturns>int</creturns>
        <cparams>VALUE<nbsp/>obj"</cparams>
        <cbody>    Returns nonzero if the given <em>obj</em> is tainted.
  </cbody>
      </cfunc>
  <cfunc name="OBJ_FREEZE">
    <creturns></creturns>
        <cparams>VALUE<nbsp/>obj"</cparams>
        <cbody>    Marks the given <em>obj</em> as frozen.
  </cbody>
      </cfunc>
  <cfunc name="OBJ_FROZEN">
    <creturns>int</creturns>
        <cparams>VALUE<nbsp/>obj"</cparams>
        <cbody>    Returns nonzero if the given <em>obj</em> is frozen.
  </cbody>
      </cfunc>
  <cfunc name="Check_SafeStr">
    <creturns></creturns>
        <cparams>VALUE<nbsp/>str"</cparams>
        <cbody>    Raises <exception>SecurityError</exception> if current safe level &gt; 0 and <em>str</em> is
    tainted, or a <exception>TypeError</exception> if <em>str</em> is not a <tt>T_STRING</tt>.
  </cbody>
      </cfunc>
  <cfunc name="rb_safe_level">
    <creturns>int</creturns>
        <cparams>"</cparams>
        <cbody>    Returns the current safe level.
  </cbody>
      </cfunc>
  <cfunc name="rb_secure">
    <creturns>void</creturns>
        <cparams>int<nbsp/>level"</cparams>
        <cbody>    Raises <exception>SecurityError</exception> if <em>level</em> &lt;= current safe level.
  </cbody>
      </cfunc>
  <cfunc name="rb_set_safe_level">
    <creturns>void</creturns>
        <cparams>int<nbsp/>newlevel"</cparams>
        <cbody>    Sets the current safe level to <em>newlevel</em>.
  </cbody>
      </cfunc>
<p/>
     </table>
<p/>
  <table>
      <cdoctitle>Commonly Used Methods</cdoctitle>
      <cfunc name="rb_ary_new">
    <creturns>VALUE</creturns>
        <cparams>"</cparams>
        <cbody>    Returns a new <classname>Array</classname> with default size.
  </cbody>
      </cfunc>
  <cfunc name="rb_ary_new2">
    <creturns>VALUE</creturns>
        <cparams>long<nbsp/>length"</cparams>
        <cbody>    Returns a new <classname>Array</classname> of the given <em>length</em>.
  </cbody>
      </cfunc>
  <cfunc name="rb_ary_new3">
    <creturns>VALUE</creturns>
        <cparams>long<nbsp/>length, ..."</cparams>
        <cbody>    Returns a new <classname>Array</classname> of the given <em>length</em> and populated
    with the remaining arguments.
  </cbody>
      </cfunc>
  <cfunc name="rb_ary_new4">
    <creturns>VALUE</creturns>
        <cparams>long<nbsp/>length, VALUE<nbsp/>*values"</cparams>
        <cbody>    Returns a new <classname>Array</classname> of the given <em>length</em> and populated
    with the C array <em>values</em>.
  </cbody>
      </cfunc>
  <cfunc name="rb_ary_store">
    <creturns>void</creturns>
        <cparams>VALUE<nbsp/>self, long<nbsp/>index, VALUE<nbsp/>value"</cparams>
        <cbody>    Stores <em>value</em> at <em>index</em> in array <em>self</em>.
  </cbody>
      </cfunc>
  <cfunc name="rb_ary_push">
    <creturns>VALUE</creturns>
        <cparams>VALUE<nbsp/>self, VALUE<nbsp/>value"</cparams>
        <cbody>    Pushes <em>value</em> onto the end of array <em>self</em>.  Returns
    <em>value</em>.
  </cbody>
      </cfunc>
  <cfunc name="rb_ary_pop">
    <creturns>VALUE</creturns>
        <cparams>VALUE<nbsp/>self"</cparams>
        <cbody>    Removes and returns the last element from the array <em>self</em>.
  </cbody>
      </cfunc>
  <cfunc name="rb_ary_shift">
    <creturns>VALUE</creturns>
        <cparams>VALUE<nbsp/>self"</cparams>
        <cbody>    Removes and returns the first element from the array <em>self</em>.
  </cbody>
      </cfunc>
  <cfunc name="rb_ary_unshift">
    <creturns>VALUE</creturns>
        <cparams>VALUE<nbsp/>self, VALUE<nbsp/>value"</cparams>
        <cbody>    Pushes <em>value</em> onto the front of array <em>self</em>.  Returns
    <em>value</em>.
  </cbody>
      </cfunc>
  <cfunc name="rb_ary_entry">
    <creturns>VALUE</creturns>
        <cparams>VALUE<nbsp/>self, long<nbsp/>index"</cparams>
        <cbody>    Returns array <em>self</em>'s element at <em>index</em>.
  </cbody>
      </cfunc>
  <cfunc name="rb_respond_to">
    <creturns>int</creturns>
        <cparams>VALUE<nbsp/>self, ID<nbsp/>method"</cparams>
        <cbody>    Returns nonzero if <em>self</em> responds to <em>method</em>.
  </cbody>
      </cfunc>
  <cfunc name="rb_thread_create">
    <creturns>VALUE</creturns>
        <cparams>VALUE<nbsp/>(*func)(), void<nbsp/>*data"</cparams>
        <cbody>    Runs <em>func</em> in a new thread, passing <em>data</em> as an
    argument.
  </cbody>
      </cfunc>
  <cfunc name="rb_hash_new">
    <creturns>VALUE</creturns>
        <cparams>"</cparams>
        <cbody>    Returns a new, empty <classname>Hash</classname>.
  </cbody>
      </cfunc>
  <cfunc name="rb_hash_aref">
    <creturns>VALUE</creturns>
        <cparams>VALUE<nbsp/>self, VALUE<nbsp/>key"</cparams>
        <cbody>    Returns the element corresponding to <em>key</em> in <em>self</em>.
  </cbody>
      </cfunc>
  <cfunc name="rb_hash_aset">
    <creturns>VALUE</creturns>
        <cparams>VALUE<nbsp/>self, VALUE<nbsp/>key, VALUE<nbsp/>value"</cparams>
        <cbody>    Sets the value for <em>key</em> to <em>value</em> in
    <em>self</em>. Returns <em>value</em>.
  </cbody>
      </cfunc>
  <cfunc name="rb_obj_is_instance_of">
    <creturns>VALUE</creturns>
        <cparams>VALUE<nbsp/>obj, VALUE<nbsp/>klass"</cparams>
        <cbody>    Returns <tt>Qtrue</tt> if <em>obj</em> is an instance of <em>klass</em>.
  </cbody>
      </cfunc>
  <cfunc name="rb_obj_is_kind_of">
    <creturns>VALUE</creturns>
        <cparams>VALUE<nbsp/>obj, VALUE<nbsp/>klass"</cparams>
        <cbody>    Returns <tt>Qtrue</tt> if <em>klass</em> is the class of <em>obj</em> or
    <em>class</em> is 
    one of the superclasses of the class of <em>obj</em>.
  </cbody>
      </cfunc>
  <cfunc name="rb_str_new">
    <creturns>VALUE</creturns>
        <cparams>const<nbsp/>char<nbsp/>*src, long<nbsp/>length"</cparams>
        <cbody>    Returns a new <classname>String</classname> initialized with <em>length</em> characters
    from <em>src</em>.
  </cbody>
      </cfunc>
  <cfunc name="rb_str_new2">
    <creturns>VALUE</creturns>
        <cparams>const<nbsp/>char<nbsp/>*src"</cparams>
        <cbody>    Returns a new <classname>String</classname> initialized with the null-terminated
    C string <em>src</em>.
  </cbody>
      </cfunc>
  <cfunc name="rb_str_dup">
    <creturns>VALUE</creturns>
        <cparams>VALUE<nbsp/>str"</cparams>
        <cbody>    Returns a new <classname>String</classname> object duplicated from <em>str</em>.
  </cbody>
      </cfunc>
  <cfunc name="rb_str_cat">
    <creturns>VALUE</creturns>
        <cparams>VALUE<nbsp/>self, const<nbsp/>char<nbsp/>*src, long<nbsp/>length"</cparams>
        <cbody>    Concatenates <em>length</em> characters from <em>src</em> onto
    the <classname>String</classname> <em>self</em>. Returns <em>self</em>.
  </cbody>
      </cfunc>
  <cfunc name="rb_str_concat">
    <creturns>VALUE</creturns>
        <cparams>VALUE<nbsp/>self, VALUE<nbsp/>other"</cparams>
        <cbody>    Concatenates <em>other</em> onto
    the <classname>String</classname> <em>self</em>. Returns <em>self</em>.
  </cbody>
      </cfunc>
  <cfunc name="rb_str_split">
    <creturns>VALUE</creturns>
        <cparams>VALUE<nbsp/>self, const<nbsp/>char<nbsp/>*delim"</cparams>
        <cbody>    Returns an array of <classname>String</classname> objects created by splitting
    <em>self</em> on <em>delim</em>.  </cbody>
      </cfunc>
<p/>
     </table>
<p/>
</chapter>
</ppdoc>
