读Ruby for Rails的思考之Ruby的C扩展库
Ruby除了用Ruby写的扩展库以外,还有许多C写的扩展库,比如socket编程库/系统日志功能库/数据库驱动这些库以.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 extensionsrequire 'mkmf'# Give it a nameextension_name = 'mytest'# The destinationdir_config(extension_name)# Do the workcreate_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 internallyVALUE MyTest = Qnil;// Prototype for the initialization method - Ruby calls this, not youvoid Init_mytest();// Prototype for our method 'test1' - methods are prefixed by 'method_' hereVALUE method_test1(VALUE self);// The initialization method for this modulevoid 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 itinclude MyTest# Call and print the result from the test1 methodputs test1# => 10
该demo程序下载地址:extension-code.tar.gz
页:
[1]