【问题标题】:How do you use the C language to produce a ruby gem?如何使用 C 语言制作 ruby​​ gem?
【发布时间】:2011-02-20 02:23:49
【问题描述】:

我想查看一些源代码,或者可能是指向一些源代码的链接,这些源代码至少提供了一个用于用 C 语言编写 ruby​​ gem 的存根(C++??这也可能吗?)

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

谢谢。

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

【问题讨论】:

  • 我建议从那里找到一个开源项目,例如 RMagick 或 Nokogiri 和婴儿床。

标签: c ruby rubygems native-code


【解决方案1】:

好的,所以我让我的一个擅长 C 的朋友坐下来。我一直在向他展示 Ruby,他很喜欢。昨晚我们见面时,我告诉他你可以用 C 编写 Ruby gem,这引起了他的兴趣。这是我们发现的:

教程/示例

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

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

根据提示,您需要通过运行 extconf.rb 创建一个 Makefile:

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

然后你可以测试一下:

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

我们做了一个基准测试,让 ruby​​ 将 3 和 4 加在一起 ​​1000 万次,然后也调用了我们的 C 扩展 1000 万次。结果是,仅使用 ruby​​ 完成这项任务需要 12 秒,而使用 C 扩展只需要 6 秒!另请注意,此处理的大部分是将作业交给 C 以完成任务。在其中一篇教程中,作者使用了递归(斐波那契数列),并报告说 C 扩展的速度快了 51 倍!

【讨论】:

    猜你喜欢
    • 2021-02-27
    • 2011-03-28
    • 2012-09-09
    • 2011-02-25
    • 1970-01-01
    • 2023-04-02
    • 2011-07-16
    • 1970-01-01
    • 2013-02-18
    相关资源
    最近更新 更多