Ruby除了用Ruby写的扩展库以外,还有许多C写的扩展库,比如socket编程库/系统日志功能库/数据库驱动
这些库以.so或者.dll结尾,这也是我们require的时候不要使用.rb后缀的原因,比如
Ruby开源项目、扩展库站点:
Ruby Application Archive(RAA)
RubyForge
怎样写Ruby的C扩展库呢?
我们来看看 How to create a Ruby extension in C under 5 minutes
该程序的前提是需要在linux/unix环境下
MyTest/extconf.rb
MyTest/MyTest.c
就这么简单,我们进入MyTest目录,运行
这会为我们创建Makefile,然后我们运行
这样我们的C扩展库就compile和build好了,让我们运行mytest.rb测试一下:
该demo程序下载地址: extension-code.tar.gz
这些库以.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