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

Ruby除了用Ruby写的扩展库以外,还有许多C写的扩展库,比如socket编程库/系统日志功能库/数据库驱动 
这些库以.so或者.dll结尾,这也是我们require的时候不要使用.rb后缀的原因,比如 
Java代码   收藏代码
  1. 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 
Java代码   收藏代码
  1. # Loads mkmf which is used to make makefiles for Ruby extensions  
  2. require 'mkmf'  
  3.   
  4. # Give it a name  
  5. extension_name = 'mytest'  
  6.   
  7. # The destination  
  8. dir_config(extension_name)  
  9.   
  10. # Do the work  
  11. create_makefile(extension_name)  

MyTest/MyTest.c 
Java代码   收藏代码
  1. // Include the Ruby headers and goodies  
  2. #include "ruby.h"  
  3.   
  4. // Defining a space for information and references about the module to be stored internally  
  5. VALUE MyTest = Qnil;  
  6.   
  7. // Prototype for the initialization method - Ruby calls this, not you  
  8. void Init_mytest();  
  9.   
  10. // Prototype for our method 'test1' - methods are prefixed by 'method_' here  
  11. VALUE method_test1(VALUE self);  
  12.   
  13. // The initialization method for this module  
  14. void Init_mytest() {  
  15.     MyTest = rb_define_module("MyTest");  
  16.     rb_define_method(MyTest, "test1", method_test1, 0);   
  17. }  
  18.   
  19. // Our 'test1' method.. it simply returns a value of '10' for now.  
  20. VALUE method_test1(VALUE self) {  
  21.     int x = 10;  
  22.     return INT2NUM(x);  
  23. }  

就这么简单,我们进入MyTest目录,运行 
Java代码   收藏代码
  1. ruby extconf.rb  

这会为我们创建Makefile,然后我们运行 
Java代码   收藏代码
  1. make  

这样我们的C扩展库就compile和build好了,让我们运行mytest.rb测试一下: 
Java代码   收藏代码
  1. # Load in the extension (on OS X this loads ./MyTest/mytest.bundle - unsure about Linux, possibly mytest.so)  
  2. require 'MyTest/mytest'  
  3.   
  4. # MyTest is now a module, so we need to include it  
  5. include MyTest  
  6.   
  7. # Call and print the result from the test1 method  
  8. puts test1  
  9.   
  10. # => 10  

该demo程序下载地址: extension-code.tar.gz
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值