2010-05-16 93 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