读Ruby for Rails的思考之Ruby的C扩展库

本文介绍了如何在Ruby中使用C语言编写扩展库,包括创建扩展库的基本步骤、必要的文件配置及编译过程。通过一个简单的示例展示了如何定义和实现自定义方法,并将其集成到Ruby环境中。
Ruby除了用Ruby写的扩展库以外,还有许多C写的扩展库,比如socket编程库/系统日志功能库/数据库驱动
这些库以.so或者.dll结尾,这也是我们require的时候不要使用.rb后缀的原因,比如
[code]
require 'gdbm'
[/code]

Ruby开源项目、扩展库站点:
[url=http://raa.ruby-lang.org]Ruby Application Archive(RAA)[/url]
[url=http://www.rubyforge.net]RubyForge[/url]

怎样写Ruby的C扩展库呢?
我们来看看[url=http://www.rubyinside.com/how-to-create-a-ruby-extension-in-c-in-under-5-minutes-100.html]How to create a Ruby extension in C under 5 minutes[/url]
该程序的前提是需要在linux/unix环境下
[b]MyTest/extconf.rb[/b]
[code]
# 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)
[/code]
[b]MyTest/MyTest.c[/b]
[code]
// 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);
}
[/code]
就这么简单,我们进入MyTest目录,运行
[code]
ruby extconf.rb
[/code]
这会为我们创建Makefile,然后我们运行
[code]
make
[/code]
这样我们的C扩展库就compile和build好了,让我们运行mytest.rb测试一下:
[code]
# 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
[/code]
该demo程序下载地址:[url=http://www.rubyinside.com/files/extension-code.tar.gz]extension-code.tar.gz[/url]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值