2010-05-16 91 views
12

我想看到一些源代码或者可能是一些链接,至少给出了一个用C语言编写红宝石的存根(C++也可能呢?)你如何使用C语言来制作红宝石宝石?

另外,你们中的一些人可能会知道Facebook将它们的一些代码原生地编译为php扩展以获得更好的性能。有人在Rails中这样做吗?如果是这样,你有什么经验呢?你觉得它有用吗?

谢谢。

编辑: 我想我会回答我的问题有一些东西,我今天学会了,但我要离开这个问题打开了另一个答案,因为我想看看别人怎么说的这个话题

+0

我会建议找到一个开源项目,如RMagick或Nokogiri和婴儿床。 – 2010-05-16 14:35:38

回答

17

好的,所以我坐下了我的一个好朋友C,我一直在向他展示Ruby,并且他挖了它。当我们昨晚见面的时候,我告诉他,你可以用C写红宝石,这让他很感兴趣。下面是我们发现:

教程/例子

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

红宝石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 

然后你把这个代码在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.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); 
} 

从提示您然后需要创建一个Makefile文件通过运行extconf.rb:

prompt>ruby extconf.rb 
prompt>make 
prompt>make install 

然后,您可以测试一下:

prompt>irb 
irb>require 'mytest' 
irb>include MyTest 
irb>add 3, 4 # => 7 

我们做了一个基准测试,并有红宝石加3个4一起1000万次,然后对通话我们的C扩展也是1000万次。结果是,只使用红宝石需要12秒来完成这项任务,而使用C扩展只需要6秒!另外请注意,大部分这些处理将作业交给C来完成任务。在其中一篇教程中,作者使用了递归(斐波那契序列)并报告C扩展花费了51倍!

+1

伟大的答案,绝对书签这,谢谢。 – Abdulaziz 2013-11-22 11:29:57