跳轉至內容

Ruby 程式設計/C 擴充套件

來自 Wikibooks,開放世界中的開放書籍

C 擴充套件

[編輯 | 編輯原始碼]

使用 C 擴充套件擴充套件 ruby 相對容易。包含在 ruby 原始碼中的 README.EXT 檔案 非常有用,它討論了建立 ruby 擴充套件,以及在 ruby 和 c 型別之間進行轉換。

通常,C 擴充套件看起來像這樣

檔案 go.c

#include "ruby.h"

void Init_go() {

}

然後,您可以使用 mkmf 庫為其建立一個 Makefile。


擴充套件配置檔案

[編輯 | 編輯原始碼]

此檔案使用 mkmf 庫建立 Makefile。然後,Makefile 與 make 程式一起使用來建立擴充套件。

一個簡單的配置檔案如下所示

檔案 config.rb

require "mkmf"

# the string is the init function's suffix in the .c source file. e.g, void Init_go()
# it's also the name of the extension. e.g, go.so
create_makefile("go")

建立擴充套件的過程

[編輯 | 編輯原始碼]

這是一個簡單的擴充套件的簡要概述,它列印經典短語“Hello!”。如果您想建立更有用的東西,則需要了解 C 並閱讀 README.EXT 檔案。

建立一個新資料夾並將下面的兩個檔案新增到其中。

檔案 hello.c

#include <ruby.h>
VALUE hello(VALUE self);

void Init_hello() {
  rb_define_global_function("hello", hello, 0);
}

VALUE hello(VALUE self)
{
  printf("Hello!\n");

  return Qnil;
}

檔案 config.rb

require 'mkmf';

# extension name
extname = 'hello';

create_makefile(extname);

現在,從命令提示符執行以下命令

ruby config.rb
make (replace with "nmake" for Windows SDK)

現在進行測試。鍵入以下內容以載入擴充套件。

irb -r .\hello.so

輸入“hello”,IRB 將回顯。

irb(main):002:0>hello
Hello!
=> nil

1.9 和 1.8 之間的區別

[編輯 | 編輯原始碼]

1.9 至少在定義了更多宏方面存在差異。以下是在 1.8 中獲取它們的方法(其中一些來自 Phusion Passenger 的程式碼)。

#ifndef RARRAY_LEN
	#define RARRAY_LEN(ary) RARRAY(ary)->len
#endif
#ifndef RSTRING_PTR
	#define RSTRING_PTR(str) RSTRING(str)->ptr
#endif
#ifndef RSTRING_LEN
	#define RSTRING_LEN(str) RSTRING(str)->len
#endif

#ifndef RBIGNUM_DIGITS
    #define RBIGNUM_DIGITS(obj) RBIGNUM(obj)->digits
#endif

JRuby 中的 C 擴充套件

[編輯 | 編輯原始碼]

您可以在 jruby 中使用 java 擴充套件(顯然)。您還可以使用 ffi 和/或 ffi-inliner gem 來使用本地 C 擴充套件。

[編輯 | 編輯原始碼]

一個教程

華夏公益教科書