ルビーfor Railsの思考を読むルビーのC拡張ライブラリ


RubyはRubyで書かれた拡張ライブラリのほか、socketプログラミングライブラリ/システムログ機能ライブラリ/データベースドライバなど、Cで書かれた拡張ライブラリがたくさんあります.
これらのライブラリは.soまたは.dllエンディング、これも私たちがrequireを使うときは使わないでください.rb接尾辞の原因、例えば

require 'gdbm'

Rubyオープンソースプロジェクト、拡張ライブラリサイト:
Ruby Application Archive(RAA)
RubyForge
RubyのC拡張ライブラリはどのように書きますか?
見てみましょう
How to create a Ruby extension in C under 5 minutes
このプログラムの前提はlinux/unix環境で
MyTest/extconf.rb

# Loads mkmf which is used to make makefiles for Ruby extensions
require 'mkmf'

# Give it a name
extension_name = 'mytest'

# The destination
dir_config(extension_name)

# Do the work
create_makefile(extension_name)

MyTest/MyTest.c

// Include the Ruby headers and goodies
#include "ruby.h"

// Defining a space for information and references about the module to be stored internally
VALUE MyTest = Qnil;

// Prototype for the initialization method - Ruby calls this, not you
void Init_mytest();

// Prototype for our method 'test1' - methods are prefixed by 'method_' here
VALUE method_test1(VALUE self);

// The initialization method for this module
void Init_mytest() {
	MyTest = rb_define_module("MyTest");
	rb_define_method(MyTest, "test1", method_test1, 0);	
}

// Our 'test1' method.. it simply returns a value of '10' for now.
VALUE method_test1(VALUE self) {
	int x = 10;
	return INT2NUM(x);
}

簡単にMyTestディレクトリにアクセスして実行します

ruby extconf.rb

Makefileを作成して実行します

make

これでC拡張ライブラリはcompileとbuildになります.mytestを実行しましょう.rbテストしてみます.

# Load in the extension (on OS X this loads ./MyTest/mytest.bundle - unsure about Linux, possibly mytest.so)
require 'MyTest/mytest'

# MyTest is now a module, so we need to include it
include MyTest

# Call and print the result from the test1 method
puts test1

# => 10

このdemoプログラムのダウンロードアドレス:
extension-code.tar.gz