目錄 搜尋
Ruby用户指南 3、开始 4、简单的例子 5、字符串 6、正则表达式 7、数组 8、回到那些简单的例子 9、流程控制 10、迭代器 11、面向对象思维 12、方法 13、类 14、继承 15、重载方法 16、访问控制 17、单态方法 18、模块 19、过程对象 20、变量 21、全局变量 22、实变量 23、局部变量 24、类常量 25、异常处理:rescue 26、异常处理:ensure 27、存取器 28、对象的初始化 29、杂项 RGSS入门教程 1、什么是RGSS 2、开始:最简单的脚本 3、数据类型:数字 4、数据类型:常量与变量 5、数据类型:字符串 6、控制语句:条件分歧语句 7、控制语句:循环 8、函数 9、对象与类 10、显示图片 11、数组 12、哈希表(关联数组) 13、类 14、数据库 15、游戏对象 16、精灵的管理 17、窗口的管理 18、活动指令 19、场景类 Programming Ruby的翻译 Programming Ruby: The Pragmatic Programmer's Guide 前言 Roadmap Ruby.new 类,对象和变量 容器Containers,块Blocks和迭代Iterators 标准类型 深入方法 表达式Expressions 异常,捕捉和抛出(已经开始,by jellen) 模块 基本输入输出 线程和进程 当遭遇挫折 Ruby和它的世界 Ruby和Web开发 Ruby Tk Ruby 和微软的 Windows 扩展Ruby Ruby语言 (by jellen) 类和对象 (by jellen) Ruby安全 反射Reflection 内建类和方法 标准库 OO设计 网络和Web库 Windows支持 内嵌文档 交互式Ruby Shell 支持 Ruby参考手册 Ruby首页 卷首语 Ruby的启动 环境变量 对象 执行 结束时的相关处理 线程 安全模型 正则表达式 字句构造 程序 变量和常数 字面值 操作符表达式 控制结构 方法调用 类/方法的定义 内部函数 内部变量 内部常数 内部类/模块/异常类 附加库 Ruby变更记录 ruby 1.6 特性 ruby 1.7 特性 Ruby术语集 Ruby的运行平台 pack模板字符串 sprintf格式 Marshal格式 Ruby FAQ Ruby的陷阱
文字

扩展Ruby



在Ruby中扩展Ruby的新功能是很容易的,如果你用c来写底层的代码,那么我们就能更好的扩展Ruby的功能。

用c来扩展ruby是非常简单的事情。比如,我们我们在为Sunset Diner and Grill建造一个基于internet的自动点唱机,它将从硬盘播放mp3文件或者从cd唱机播放cd音频。我们想从ruby程序中控制硬件系统,硬件提供商为我们提供了一个C语言的头文件,和一个二进制的实现库文件,我们所需要做的是创建一个Ruby对象,映射到相应的C函数调用。

在进一步使Ruby和C语言一起工作之前,先让我们从c语言角度看看ruby对象是什么样的。[本章又很多信息都是从随同ruby发布的 README.EXT摘录的,如果你想扩展ruby的话,可以参考最新版本的README.EXT]

C语言中的Ruby对象

我们要看的第一件事情是在C语言中如何表示和访问Ruby的数据类型。Ruby中所有东西都是对象,所有的变量都指向一个对象。在C语言中,所有Ruby变量的类型都是VALUE,它要们是一个指向Ruby对象的指针,要们指向一个立即值(immediate value),比如Fixnum。

这也是Ruby如何在C中实现面向对象的代码的:一个Ruby对象是在内存中分配的一个结构,这个结构包括一个包括实例变量的表,和关于关于类的信息。这个类本身是另一个对象(分配了内存结构),有一个包括类中方法定义的表。

VALUE 是一个指针

VALUE 是一个指针指向一个定义好的Ruby对象结构,而不能指向其他类型的结构。每个Ruby内建的类的结构定义在"ruby.h"中,命名都以R开头加类名,比如RString和RArray。

有几种办法来判断一个VALUE所对应的结构的类型。宏TYPE( obj )可以返回代表指定对象的C类型的常量的值:T_OBJECT, T_STRING或其它。代表内建类的常量在ruby.h中定义。注意这里我们说得类型是实现上的细节,而不是向某一个对象的类。(Note that the type we are referring to here is an implementation detail---it is not the same as the class of an object.)

 如果你想确认一个vaulue指针指向一个特定的结构,你可以用宏Check_Type。如果给定的value不是type型的,将会产生一个TypeError 的异常。(type是T_STRING, T_FLOAT或其它)。

Check_Type(VALUE value, int type)

如果你很关心速度,这里有一些很快的宏来判断立即值Fixnumnil:
FIXNUM_P(value) -> non-zero if value is a Fixnum
NIL_P(value)    -> non-zero if value is nil
RTEST(value)    -> non-zero if value is neither nil nor false

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 rb_c Classname (for instance, rb_cObject); modules are named rb_m Modulename.

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).

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 VALUE to the proper structure type. ruby.h contains a number of macros that perform the proper casting for you, allowing you to dereference structure members easily. These macros are named RCLASSNAME , as in RSTRING or RARRAY. For example:

VALUE str, arr;
RSTRING(str)->len -> length of the Ruby string
RSTRING(str)->ptr -> pointer to string storage
RARRAY(arr)->len  -> length of the Ruby array
RARRAY(arr)->capa -> capacity of the Ruby array
RARRAY(arr)->ptr  -> pointer to array storage

VALUE 作为立即对象(Immediate Object)

我们上面说过,立即值不是指针:: Fixnum, Symbol, true, false, 和 nil 直接存储在 VALUE中。

Fixnum 值在存储器中占用31个bit(其他的cpu结构可能占用63个bit),然后这个值左移一位,最后一位设置为 "1",当VAULE指向其他类型的数据时,这个最低位(LSB)总是"0",其他的立即值得LSB也是0,这样,可以通过这个位的值是0还是1来判断这个值是不是Fixnum。

其它的立即值true, false, nil在C语言中用常量Qtrue, Qfalse, Qnil来表示,你可以用这些常量来测试一个值是不是true,false,nil等,或者用转换宏来测试。

Writing Ruby in C

用Ruby编程的乐趣之一是你可以在C语言里像Ruby中一样实现,你可以用同样的方法名,同样的逻辑,除了一些语法的区别,比如,这里有一个用Ruby写的简单的test类:

class Test
  def initialize
    @arr = Array.new
  end
  def add(anObject)
    @arr.push(anObject)
  end
end

完成上面同样功能的C代码如下:

#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);         
}

让我们详细的看看这里面的细节,这段程序包括了本章的很多重要的内容。首先,我们需要把ruby.h文件引入,才能使用其中的一些预定义的东西。

然后来看看最后一个函数:Init_Test。每个类或模块都要定义一个C的全局函数 Init_name局函,这个函数将会在ruby解释器第一次载入扩展name的时候执行,它用来初始化这个扩展(extension ),使它融入Ruby的环境中。这个例子里,我们定义了一个类Test,它是Object的子类。(Object在ruby.h中用rb_cObject表示)

然后我们建立了两个函数add和initialize,这两个都是类Test的实例方法。函数rb_define_method 绑定了Ruby中的方法和对应的C语言的实现。所以,在Ruby中调用这个类的add方法,将会调用C函数t_add。

类似的,当在Ruby中调用Test的new方法时,将会调用initialize方法,也就是C程序里面的t_init方法(没有Ruby参数)。

 现在回来看看方法initialize的定义,我们说过它不需要参数,但是那里却真的有一个参数。除了ruby方法中的参数,每个方法都会被传递一个最初的VALUE参数,这个VALUE指的是方法的接收者(receiver ),类似Ruby中的self。

initialize 方法中我们做的是创建一个Ruby中的数组,并用实例变量@arr指向这个数组。 Just as you would expect if you were writing Ruby source, referencing an instance variable that doesn't exist creates it.

最后,t_add方法从当前对象取得实例变量@arr,并用 Array#push 把传递过来的参数放到里面。当用这种方法访问实例变量的时候,前缀@是必不可少的,否则在Ruby中将不能访问这个变量。

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.

警告: 从Ruby中能访问的C语言中的所有方法都必须返回一个VALUE值,即使Qnil也行。否则会出现core dump。

要想在Ruby中使用上面的C代码,只需要动态的把它require进来就行。

require "code/ext/Test"
t = Test.new
t.add("Bill Chase")
C/Ruby 类型转换函数和宏
C 类型转换到 Ruby:
INT2NUM(int) -> Fixnum or Bignum
INT2FIX(int) -> Fixnum (faster)
INT2NUM(long or int) -> Fixnum or Bignum
INT2FIX(long or int) -> Fixnum (faster)
CHR2FIX(char) -> Fixnum
rb_str_new2(char *) -> String
rb_float_new(double) -> Float
从Ruby对象转换到C的数据类型:
int NUM2INT(Numeric) (Includes type check)
int FIX2INT(Fixnum) (Faster)
unsigned int NUM2UINT(Numeric) (Includes type check)
unsigned int FIX2UINT(Fixnum) (Includes type check)
long NUM2LONG(Numeric) (Includes type check)
long FIX2LONG(Fixnum) (Faster)
unsigned long NUM2ULONG(Numeric) (Includes type check)
char NUM2CHR(Numeric or String) (Includes type check)
char * STR2CSTR(String)
char * rb_str2cstr(String, int *length) Returns length as well
double NUM2DBL(Numeric)

在C语言中运行Ruby表达式

如果你在C语言中编程,而且需要用到一些Ruby的表达式,但是不想写一段代码来实现,你可以用C版本的eval。假如你有一个数组,需要把里面的flag标志都清除:

rb_eval_string("anObject.each{|x| x.clearFlag }");

如果你只是想调用一个特别的方法,可以这样:

If you just want to call a particular method (which is cheaper than eval-ing an entire string) you can use

rb_funcall(receiver, method_id, argc, ...)

在Ruby 和 C之间共享数据

我们已经涉及到了很多基础的东西,现在来看看我们自动点唱机的例子,我们要用Ruby包装C代码,还要在两种语言之间共享数据。

直接共享变量

尽管你可以在C中和Ruby中各维护一个变量,并保持它们之间的同步,但是这样做是不可取得,违反了DRY(Don't Repeat Yourself)原则。更好的方法是直接在Ruby和C之间共享一个变量,你可以通过在C语言里面创建一个Ruby对象,然后把它绑定到一个Ruby中地全局变量来共享一个全局变量,在这种情况下,"$"是可选的,但是为了阅读方便最好还是在前面加上"$"。

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"));

然后,在Ruby中就可以$hardware来访问C语言中的变量hardware_list。

$hardware ? ["DVD", "CDPlayer1", "CDPlayer2"]

You can also create hooked variables that will call a specified function when the variable is accessed, and virtual variables that only call the hooks---no actual variable is involved. See the API section that begins on page 189 for details.

If you create a Ruby object from C and store it in a C global variable without exporting it to Ruby, you must at least tell the garbage collector about it, lest ye be reaped inadvertently:

VALUE obj;
obj = rb_ary_new();
rb_global_variable(obj);

包装C结构(Wrapping C Structures)

Now on to the really 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:

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);
   

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 CDJukeBox 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.

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 DATA (type T_DATA). There are two macros to do this wrapping, and one to retrieve your structure back out again.

C Datatype Wrapping
VALUE  Data_Wrap_Struct(VALUE class, void (*mark)(), void (*free)(), void *ptr")
  Wraps the given C datatype ptr, 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 T_DATA and its Ruby class is class.
VALUE  Data_Make_Struct(VALUE class, c-type, void (*mark)(), void (*free)(), c-type *")
  Allocates a structure of the indicated type first, then proceeds as Data_Wrap_Struct. c-type is the name of the C datatype that you're wrapping, not a variable of that type.
  Data_Get_Struct(VALUE obj,c-type,c-type *")
  Returns the original pointer. This macro is a type-safe wrapper around the macro DATA_PTR(obj), which evaluates the pointer.

The object created by Data_Wrap_Struct 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 not available...

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 void pointer, a reference to your structure. The mark 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 rb_gc_mark(value). If the structure doesn't reference other Ruby objects, you can simply pass 0 as a function pointer.

When the object needs to be disposed of, the garbage collector will call the free routine to free it. If you have allocated any memory yourself (for instance, by using Data_Make_Struct), you'll need to pass a free function---even if it's just the standard C library's free routine. For complex structures that you have allocated, your free function may need to traverse the structure to free all the allocated memory.

First a simple example, without any special handling. Given the structure definition

typedef struct mp3info {
  char *title;
  char *artist;
  int  genre;
} MP3Info;

we can create a structure, populate it, and wrap it as an object.[We cheat a bit in this example. Our MP3Info structure has a couple of char 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 MP3Info structure is freed. If we'd allocated these strings dynamically, we'd have to write a free method to dispose of them.]

MP3Info *p;
VALUE info;

p = ALLOC(MP3Info);             
p->artist = "Maynard Ferguson";             
p->title = "Chameleon";             
...             
info = Data_Wrap_Struct(cTest, 0, free, p);
 

info is a VALUE type, a genuine Ruby object of class Test (represented in C by the built-in type T_DATA). 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 VALUE:

VALUE doit(VALUE info) {
  MP3Info *p;
  Data_Get_Struct(info, MP3Info, p);
  ...
  p->artist    -> "Maynard Ferguson"
  p->title     -> "Chameleon"
  ...
}

In order to follow convention, however, you may need a few more things: support for an initialize method, and a ``C-constructor.'' If you were writing Ruby source, you'd allocate and initialize an object by calling new. In C extensions, the corresponding call is Data_Make_Struct. However, although this allocates memory for the object, it does not automatically call an initialize method; you need to do that yourself:

info = Data_Make_Struct(cTest, MP3Info, 0, free, one);
rb_obj_call_init(info, argc, argv);

This has the benefit of allowing subclasses in Ruby to override or augment the basic initialize in your class. Within initialize, it is allowable (but not necessarily advisable) to alter the existing data pointer, which may be accessed directly with DATA_PTR(obj).

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 rb_str_new, rb_ary_new, and so on. We can make our own:

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;
}

An Example

Okay, now we're ready for a full-size example. Given our vendor's header file above, we write the following code.

#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); 
}
      

Now we have the ability to control our jukebox from Ruby in a nice, object-oriented manner:

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"
produces:
Unit is 1
26% done
79% done
100% done
Avg. time was 1.2 seconds

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 seek. In the progress 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.

Memory Allocation

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.

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 malloc. For instance, if ALLOC_N 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 NoMemError if it can't or if the requested amount of memory is invalid.

Memory Allocation
type *  ALLOC_N(c-type, n")
  Allocates n c-type objects, where c-type is the literal name of the C type, not a variable of that type.
type *  ALLOC(c-type")
  Allocates a c-type and casts the result to a pointer of that type.
  REALLOC_N(var, c-type, n")
  Reallocates n c-types and assigns the result to var, a pointer to a c-type.
type *  ALLOCA_N(c-type, n")
  Allocates memory for n objects of c-type on the stack---this memory will be automatically freed when the function that invokes ALLOCA_N returns.

创建扩展程序

写完了需要的源代码,我们需要编译它,以使Ruby程序可以访问它。我们可以把它编译成共享的对象,在运行时候动态装载;或者把它静态的连接到Ruby解释器本身。基本的过程都已眼:

  • 在给定的目录写好源代码。
  • 创建 extconf.rb文件。
  • 运行extconf.rb创建 Makefile,用来编译C文件。
  • 运行make
  • 运行 make install

用 extconf.rb创建Makefile 

上面看到的创建一个Ruby扩展程序的过程中,主要的步骤是作为程序员写的extconf.rb。在这个程序里,需要判断当前系统需要支持哪些特性,以及这些特性的位置。运行extconf.rb程序将产生一个Makefile文件,这是一个根据用户的需求和系统属性定制文件。当你运行make程序时,我们创建的扩展程序将会被编译(也可能被安装到某个地方)。

最简单的extconf.rb有可能只有两行长,并且,对很多Ruby扩展程序来说,这两行足够了:

require 'mkmf'
create_makefile("Test")

第一行引入了模块"mkmf",这个模块有我们要用到的各种命令。第二行为扩展程序"Test"创建了一个Makefile文件。(注意"Test"是扩展程序的名字,而Makefile一直都是这个名字)。Test将会在这个目录被编译。

Let's say that we run this extconf.rb program in a directory containing a single source file, main.c. The result is a Makefile that will build our extension. On our system, this contains the following commands.

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

The result of this compilation is Test.so, which may be dynamically linked into Ruby at runtime with ``require''. See how the mkmf commands have located platform-specific libraries and used compiler-specific options automatically. Pretty neat, eh?

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.

A common requirement is to specify nonstandard directories where include files and libraries may be found. This is a two-step process. First, your extconf.rb should contain one or more dir_config commands. This specifies a tag for a set of directories. Then, when you run the extconf.rb program, you tell mkmf where the corresponding physical directories are on the current system.

If extconf.rb contains the line dir_config( name ), then you give the location of the corresponding directories with the command-line options:

--with-name-include=directory

* Add directory/include to the compile command.
--with-name-lib=directory

* Add directory/lib to the link command.

If (as is common) your include and library directories are both subdirectories of some other directory, and (as is also common) they're called include and lib, you can take a shortcut:

--with-name-dir=directory

* Add directory/lib and directory/include to the link command and compile command, respectively.

There's a twist here. As well as specifying all these --with options when you run extconf.rb, you can also use the --with 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.

To make all this concrete, lets say you need to use libraries and include files for the CD jukebox we're developing. Your extconf.rb program might contain

require 'mkmf'
dir_config('cdjukebox')
# .. more stuff
create_makefile("CDJukeBox")

You'd then run extconf.rb with something like:

% ruby extconf.rb --with-cdjukebox-dir=/usr/local/cdjb

The generated Makefile would assume that the libraries were in /usr/local/cdjb/lib and the include files were in /usr/local/cdjb/include.

The dir_config 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 have_library or find_library commands.

have_library 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. find_library is similar, but allows you to specify a list of directories to search for the library.

require 'mkmf'
dir_config('cdjukebox')
have_library('cdjb', 'CDPlayerNew')
create_makefile("CDJukeBox")

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 find_library command will search a list of supplied directories to find the right one (this is different from have_library, which uses only configuration information for the search). For example, to create a Makefile that uses X Windows and a jpeg library, extconf.rb might contain

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

We've added some additional functionality to this program. All of the mkmf commands return false if they fail. This means that we can write an extconf.rb that generates a Makefile 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.

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.

require 'mkmf'
dir_config('cdjukebox')
have_library('cdjb', 'CDPlayerNew')
have_header('hp_mp3.h')
create_makefile("CDJukeBox")

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 setpriority call would be useful but isn't always available. We can check for it with:

require 'mkmf'
dir_config('cdjukebox')
have_func('setpriority')
create_makefile("CDJukeBox")

Both have_header and have_func 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:

#if defined(HAVE_HP_MP3_H)
#  include <hp_mp3.h>
#endif



#if defined(HAVE_SETPRIORITY)                 
  err = setpriority(PRIOR_PROCESS, 0, -10)                 
#endif

If you have special requirements that can't be met with all these mkmf commands, your program can directly add to the global variables $CFLAGS and $LFLAGS, which are passed to the compiler and linker, respectively.

静态连接 Static Linking

最后,如果你的系统不支持动态连接,或者你想你的扩展程序静态的连接到Ruby本身,编辑Ruby发行版本中的ext目录下的Setup文件,把你的扩展程序的目录加进去,然后重新编译Ruby。在Setup文件中列出来的扩展程序都会被静态的连接到Ruby可执行程序。如果你不想支持任何动态连接,你可以编辑Setup文件让它只包含一行:

option nodynamic

Embedding a Ruby Interpreter

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.

#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 */           
  }           
}
 

To initialize the Ruby interpreter, you need to call ruby_init(). But on some platforms, you may need to take special steps before that:

#if defined(NT)
  NtInitialize(&argc, &argv);
#endif
#if defined(__MACOS__) && defined(__MWERKS__)
  argc = ccommand(&argv);
#endif

See main.c in the Ruby distribution for any other special defines or setup needed for your platform.

Embedded Ruby API
void  ruby_init(")
  Sets up and initializes the interpreter. This function should be called before any other Ruby-related functions.
void  ruby_options(int argc, char **argv")
  Gives the Ruby interpreter the command-line options.
void  ruby_script(char *name")
  Sets the name of the Ruby script (and $0) to name.
void  rb_load_file(char *file")
  Loads the given file into the interpreter.
void  ruby_run(")
  Runs the interpreter.

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. rb_protect, rb_rescue, and related functions are documented on page 192.

For an example of embedding a Ruby interpreter within another program, see also eruby, which is described beginning on page 147.

Bridging Ruby to Other Languages

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.

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.

Ruby C Language API

Last, but by no means least, here are several C-level functions that you may find useful when writing an extension.

Some functions require an ID: you can obtain an ID for a string by using rb_intern and reconstruct the name from an ID by using rb_id2name.

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.

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 ``ruby.h'' or ``intern.h'' 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 README.EXT, shows the main source files in the interpreter.

Ruby Language Core

class.c error.c eval.c gc.c object.c parse.y variable.c
Utility Functions

dln.c regex.c st.c util.c
Ruby Interpreter

dmyext.c inits.c keywords main.c ruby.c version.c
Base Library

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

Defining Objects
VALUE  rb_define_class(char *name, VALUE superclass")
  Defines a new class at the top level with the given name and superclass (for class Object, use rb_cObject).
VALUE  rb_define_module(char *name")
  Defines a new module at the top level with the given name.
VALUE  rb_define_class_under(VALUE under, char *name, VALUE superclass")
  Defines a nested class under the class or module under.
VALUE  rb_define_module_under(VALUE under, char *name")
  Defines a nested module under the class or module under.
void  rb_include_module(VALUE parent, VALUE module")
  Includes the given module into the class or module parent.
void  rb_extend_object(VALUE obj, VALUE module")
  Extends obj with module.
VALUE  rb_require(const char *name")
  Equivalent to ``require name.'' Returns Qtrue or Qfalse.

In some of the function definitions that follow, the parameter argc specifies how many arguments a Ruby method takes. It may have the following values.

argc Function prototype
0..17 VALUE func(VALUE self, VALUE arg...)
The C function will be called with this many actual arguments.
-1 VALUE func(int argc, VALUE *argv, VALUE self)
The C function will be given a variable number of arguments passed as a C array.
-2 VALUE func(VALUE self, VALUE args)
The C function will be given a variable number of arguments passed as a Ruby array.

In a function that has been given a variable number of arguments, you can use the C function rb_scan_args to sort things out (see below).

Defining Methods
void  rb_define_method(VALUE classmod, char *name, VALUE(*func)(), int argc")
  Defines an instance method in the class or module classmod with the given name, implemented by the C function func and taking argc arguments.
void  rb_define_module_function(VALUE classmod, char *name, VALUE(*func)(), int argc)")
  Defines a method in class classmod with the given name, implemented by the C function func and taking argc arguments.
void  rb_define_global_function(char *name, VALUE(*func)(), int argc")
  Defines a global function (a private method of Kernel) with the given name, implemented by the C function func and taking argc arguments.
void  rb_define_singleton_method(VALUE classmod, char *name, VALUE(*func)(), int argc")
  Defines a singleton method in class classmod with the given name, implemented by the C function func and taking argc arguments.
int  rb_scan_args(int argcount, VALUE *argv, char *fmt, ...")
  Scans the argument list and assigns to variables similar to scanf: fmt 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 ``&'' means that an attached code block will be taken and assigned to the given variable (if no code block was given, Qnil will be assigned). After the fmt string, pointers to VALUE are given (as with scanf) to which the arguments are assigned.

VALUE name, one, two, rest;
rb_scan_args(argc, argv, "12", &name, &one, &two);
rb_scan_args(argc, argv, "1*", &name, &rest);
void  rb_undef_method(VALUE classmod, const char *name")
  Undefines the given method name in the given classmod class or module.
void  rb_define_alias(VALUE classmod, const char *newname, const char *oldname")
  Defines an alias for oldname in class or module classmod.

Defining Variables and Constants
void  rb_define_const(VALUE classmod, char *name, VALUE value")
  Defines a constant in the class or module classmod, with the given name and value.
void  rb_define_global_const(char *name, VALUE value")
  Defines a global constant with the given name and value.
void  rb_define_variable(const char *name, VALUE *object")
  Exports the address of the given object that was created in C to the Ruby namespace as name. From Ruby, this will be a global variable, so name 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.
void  rb_define_class_variable(VALUE class, const char *name, VALUE val")
  Defines a class variable name (which must be specified with a ``@@'' prefix) in the given class, initialized to value.
void  rb_define_virtual_variable(const char *name, VALUE(*getter)(), void(*setter)()")
  Exports a virtual variable to Ruby namespace as the global $name. No actual storage exists for the variable; attempts to get and set the value will call the given functions with the prototypes:

VALUE getter(ID id, VALUE *data,
             struct global_entry *entry);
void setter(VALUE value, ID id, VALUE *data,
            struct global_entry *entry);

You will likely not need to use the entry parameter and can safely omit it from your function declarations.
void  rb_define_hooked_variable(const char *name, VALUE *variable, VALUE(*getter)(), void(*setter)()")
  Defines functions to be called when reading or writing to variable. See also rb_define_virtual_variable.
void  rb_define_readonly_variable(const char *name, VALUE *value")
  Same as rb_define_variable, but read-only from Ruby.
void  rb_define_attr(VALUE variable, const char *name, int read, int write")
  Creates accessor methods for the given variable, with the given name. If read is nonzero, create a read method; if write is nonzero, create a write method.
void  rb_global_variable(VALUE *obj")
  Registers the given address with the garbage collector.

Calling Methods
VALUE  rb_funcall(VALUE recv, ID id, int argc, ...")
  Invokes the method given by id in the object recv with the given number of arguments argc and the arguments themselves (possibly none).
VALUE  rb_funcall2(VALUE recv, ID id, int argc, VALUE *args")
  Invokes the method given by id in the object recv with the given number of arguments argc and the arguments themselves given in the C array args.
VALUE  rb_funcall3(VALUE recv, ID id, int argc, VALUE *args")
  Same as rb_funcall2, but will not call private methods.
VALUE  rb_apply(VALUE recv, ID name, int argc, VALUE args")
  Invokes the method given by id in the object recv with the given number of arguments argc and the arguments themselves given in the Ruby Array args.
ID  rb_intern(char *name")
  Returns an ID for a given name. If the name does not exist, a symbol table entry will be created for it.
char *  rb_id2name(ID id")
  Returns a name for the given id.
VALUE  rb_call_super(int argc, VALUE *args")
  Calls the current method in the superclass of the current object.

Exceptions
void  rb_raise(VALUE exception, const char *fmt, ...")
  Raises an exception. The given string fmt and remaining arguments are interpreted as with printf.
void  rb_fatal(const char *fmt, ...")
  Raises a Fatal exception, terminating the process. No rescue blocks are called, but ensure blocks will be called. The given string fmt and remaining arguments are interpreted as with printf.
void  rb_bug(const char *fmt, ...")
  Terminates the process immediately---no handlers of any sort will be called. The given string fmt and remaining arguments are interpreted as with printf. You should call this function only if a fatal bug has been exposed. You don't write fatal bugs, do you?
void  rb_sys_fail(const char *msg")
  Raises a platform-specific exception corresponding to the last known system error, with the given msg.
VALUE  rb_rescue(VALUE (*body)(), VALUE args, VALUE(*rescue)(), VALUE rargs")
  Executes body with the given args. If a StandardError exception is raised, then execute rescue with the given rargs.
VALUE  rb_ensure(VALUE(*body)(), VALUE args, VALUE(*ensure)(), VALUE eargs")
  Executes body with the given args. Whether or not an exception is raised, execute ensure with the given rargs after body has completed.
VALUE  rb_protect(VALUE (*body)(), VALUE args, int *result")
  Executes body with the given args and returns nonzero in result if any exception was raised.
void  rb_notimplement(")
  Raises a NotImpError exception to indicate that the enclosed function is not implemented yet, or not available on this platform.
void  rb_exit(int status")
  Exits Ruby with the given status. Raises a SystemExit exception and calls registered exit functions and finalizers.
void  rb_warn(const char *fmt, ...")
  Unconditionally issues a warning message to standard error. The given string fmt and remaining arguments are interpreted as with printf.
void  rb_warning(const char *fmt, ...")
  Conditionally issues a warning message to standard error if Ruby was invoked with the -w flag. The given string fmt and remaining arguments are interpreted as with printf.

Iterators
void  rb_iter_break(")
  Breaks out of the enclosing iterator block.
VALUE  rb_each(VALUE obj")
  Invokes the each method of the given obj.
VALUE  rb_yield(VALUE arg")
  Transfers execution to the iterator block in the current context, passing arg as an argument. Multiple values may be passed in an array.
int  rb_block_given_p(")
  Returns true if yield 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.
VALUE  rb_iterate(VALUE (*method)(), VALUE args, VALUE (*block)(), VALUE arg2")
  Invokes method with argument args and block block. A yield from that method will invoke block with the argument given to yield, and a second argument arg2.
VALUE  rb_catch(const char *tag, VALUE (*proc)(), VALUE value")
  Equivalent to Ruby catch.
void  rb_throw(const char *tag , VALUE value")
  Equivalent to Ruby throw.

Accessing Variables
VALUE  rb_iv_get(VALUE obj, char *name")
  Returns the instance variable name (which must be specified with a ``@'' prefix) from the given obj.
VALUE  rb_ivar_get(VALUE obj, ID name")
  Returns the instance variable name from the given obj.
VALUE  rb_iv_set(VALUE obj, char *name, VALUE value")
  Sets the value of the instance variable name (which must be specified with a ``@'' prefix) in the given obj to value. Returns value.
VALUE  rb_ivar_set(VALUE obj, ID name, VALUE value")
  Sets the value of the instance variable name in the given obj to value. Returns value.
VALUE  rb_gv_set(const char *name, VALUE value")
  Sets the global variable name (the ``$'' prefix is optional) to value. Returns value.
VALUE  rb_gv_get(const char *name")
  Returns the global variable name (the ``$'' prefix is optional).
void  rb_cvar_set(VALUE class, ID name, VALUE val")
  Sets the class variable name in the given class to value.
VALUE  rb_cvar_get(VALUE class, ID name")
  Returns the class variable name from the given class.
int  rb_cvar_defined(VALUE class, ID name")
  Returns Qtrue if the given class variable name has been defined for class; otherwise, returns Qfalse.
void  rb_cv_set(VALUE class, const char *name, VALUE val")
  Sets the class variable name (which must be specified with a ``@@'' prefix) in the given class to value.
VALUE  rb_cv_get(VALUE class, const char *name")
  Returns the class variable name (which must be specified with a ``@@'' prefix) from the given class.

Object Status
  OBJ_TAINT(VALUE obj")
  Marks the given obj as tainted.
int  OBJ_TAINTED(VALUE obj")
  Returns nonzero if the given obj is tainted.
  OBJ_FREEZE(VALUE obj")
  Marks the given obj as frozen.
int  OBJ_FROZEN(VALUE obj")
  Returns nonzero if the given obj is frozen.
  Check_SafeStr(VALUE str")
  Raises SecurityError if current safe level > 0 and str is tainted, or a TypeError if str is not a T_STRING.
int  rb_safe_level(")
  Returns the current safe level.
void  rb_secure(int level")
  Raises SecurityError if level <= current safe level.
void  rb_set_safe_level(int newlevel")
  Sets the current safe level to newlevel.

Commonly Used Methods
VALUE  rb_ary_new(")
  Returns a new Array with default size.
VALUE  rb_ary_new2(long length")
  Returns a new Array of the given length.
VALUE  rb_ary_new3(long length, ...")
  Returns a new Array of the given length and populated with the remaining arguments.
VALUE  rb_ary_new4(long length, VALUE *values")
  Returns a new Array of the given length and populated with the C array values.
void  rb_ary_store(VALUE self, long index, VALUE value")
  Stores value at index in array self.
VALUE  rb_ary_push(VALUE self, VALUE value")
  Pushes value onto the end of array self. Returns value.
VALUE  rb_ary_pop(VALUE self")
  Removes and returns the last element from the array self.
VALUE  rb_ary_shift(VALUE self")
  Removes and returns the first element from the array self.
VALUE  rb_ary_unshift(VALUE self, VALUE value")
  Pushes value onto the front of array self. Returns value.
VALUE  rb_ary_entry(VALUE self, long index")
  Returns array self's element at index.
int  rb_respond_to(VALUE self, ID method")
  Returns nonzero if self responds to method.
VALUE  rb_thread_create(VALUE (*func)(), void *data")
  Runs func in a new thread, passing data as an argument.
VALUE  rb_hash_new(")
  Returns a new, empty Hash.
VALUE  rb_hash_aref(VALUE self, VALUE key")
  Returns the element corresponding to key in self.
VALUE  rb_hash_aset(VALUE self, VALUE key, VALUE value")
  Sets the value for key to value in self. Returns value.
VALUE  rb_obj_is_instance_of(VALUE obj, VALUE klass")
  Returns Qtrue if obj is an instance of klass.
VALUE  rb_obj_is_kind_of(VALUE obj, VALUE klass")
  Returns Qtrue if klass is the class of obj or class is one of the superclasses of the class of obj.
VALUE  rb_str_new(const char *src, long length")
  Returns a new String initialized with length characters from src.
VALUE  rb_str_new2(const char *src")
  Returns a new String initialized with the null-terminated C string src.
VALUE  rb_str_dup(VALUE str")
  Returns a new String object duplicated from str.
VALUE  rb_str_cat(VALUE self, const char *src, long length")
  Concatenates length characters from src onto the String self. Returns self.
VALUE  rb_str_concat(VALUE self, VALUE other")
  Concatenates other onto the String self. Returns self.
VALUE  rb_str_split(VALUE self, const char *delim")
  Returns an array of String objects created by splitting self on delim.


Extracted from the book "Programming Ruby - The Pragmatic Programmer's Guide"
Copyright © 2001 by Addison Wesley Longman, Inc. 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/)).

Distribution of substantively modified versions of this document is prohibited without the explicit permission of the copyright holder.

Distribution of the work or derivative of the work in any standard (paper) book form is prohibited unless prior permission is obtained from the copyright holder.
上一篇: 下一篇: