gpt4 book ai didi

c - 如何使用 C 语言制作 ruby​​ gem?

转载 作者:数据小太阳 更新时间:2023-10-29 06:39:20 25 4
gpt4 key购买 nike

我希望看到一些源代码或者一些链接,至少可以提供一个用 C 语言编写 ruby​​ gems 的 stub (C++??这也可能吗?)

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

谢谢。

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

最佳答案

好的,所以我找了一个擅长 C 语言的 friend 。我一直在向他展示 Ruby,他很喜欢。当我们昨晚见面时,我告诉他你可以用 C 编写 Ruby gems,这引起了他的兴趣。这是我们的发现:

教程/示例

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 倍!

关于c - 如何使用 C 语言制作 ruby​​ gem?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2843965/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com