你如何使用C语言来制作红宝石?

aar*_*ona 13 c ruby rubygems native-code

我想看一些源代码或者某些链接,它们至少提供了一个用于在C语言中编写ruby gems的存根(C++ ??也可能吗?)

此外,你们中的一些人可能知道Facebook本身编译了一些代码作为php扩展以获得更好的性能.有人在Rails中这样做吗?如果是这样,您的体验是什么?你发现它有用吗?

谢谢.

编辑: 我想我会用我今天学到的一些东西回答我自己的问题,但是我会把问题留给另一个答案,因为我想看看别人对这个话题有什么看法

aar*_*ona 17

好吧,所以我坐下了我的好朋友,这对我来说很好.我一直在向他展示Ruby,他挖掘了它.当我们昨晚见面时,我告诉他你可以用C写Ruby宝石,这引起了他的兴趣.这是我们发现的:

教程/示例

http://www.eqqon.com/index.php/Ruby_C_Extension

http://drnicwilliams.com/2008/04/01/writing-c-extensions-in-rubygems/

http://www.rubyinside.com/how-to-create-a-ruby-extension-in-c-in-under-5-minutes-100.html

ruby-doc(ruby.h源代码)

http://ruby-doc.org/doxygen/1.8.4/ruby_8h-source.html

以下是我们编写的一些源代码,用于测试它:

打开终端:

prompt>mkdir MyTest
prompt>cd MyTest
prompt>gedit extconf.rb
Run Code Online (Sandbox Code Playgroud)

然后将此代码放在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)
Run Code Online (Sandbox Code Playgroud)

保存文件,然后编写MyTest.c

#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);
VALUE method_add(VALUE, VALUE, VALUE);

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

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

// This is the method we added to test out passing parameters
VALUE method_add(VALUE self, VALUE first, VALUE second) {
int a = NUM2INT(first);
int b = NUM2INT(second);
return INT2NUM(a + b);
}
Run Code Online (Sandbox Code Playgroud)

从提示中,您需要通过运行extconf.rb来创建Makefile:

prompt>ruby extconf.rb
prompt>make
prompt>make install
Run Code Online (Sandbox Code Playgroud)

然后你可以测试它:

prompt>irb
irb>require 'mytest'
irb>include MyTest
irb>add 3, 4 # => 7
Run Code Online (Sandbox Code Playgroud)

我们做了一个基准测试,并且ruby将3和4加在一起1000万次,然后拨打我们的C扩展1000万次.结果是仅使用ruby完成此任务需要12秒,而使用C扩展只需要6秒!另请注意,此处理的大部分是将作业交给C以完成任务.在其中一个教程中,作者使用递归(Fibonacci序列)并报告C扩展速度快了51倍!