如何红宝石数组转换为C数组了RubyInline? [英] How to convert ruby array to C array with RubyInline?

查看:172
本文介绍了如何红宝石数组转换为C数组了RubyInline?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个比较两个字符串成炭烧焦的功能。我需要它运行速度远远超过它在Ruby中,所以我用了RubyInline重写C中的功能,它确实增加了大约100倍的速度。功能如下:

I have a function which compares 2 strings char by char. I needed it to run much faster than it is in Ruby so I used RubyInline to rewrite the function in C. It did increase the speed about 100 fold. The function looks like this:

  require 'inline'

  inline do |builder|
    builder.c "
      static int distance(char *s, char *t){
        ...
      }"
  end

不过,我需要比较UNI code字符串。所以,我决定用解压(U *),并比较整数数组来代替。我无法从微薄的文档了RubyInline弄清楚如何红宝石数组传递到函数以及如何将它们转换为C数组。任何帮助AP preciated!

however I need to compare unicode strings. So I decided to use unpack("U*") and compare arrays of integers instead. I cannot figure out from a scanty documentation to RubyInline how to pass the ruby arrays into the function and how to convert them into C arrays. Any help is appreciated!

推荐答案

这有如何访问红宝石从C对象的好纲要:<一href=\"http://rubycentral.com/pickaxe/ext%5Fruby.html\">http://rubycentral.com/pickaxe/ext_ruby.html

This has a good rundown of how to access Ruby objects from C: http://rubycentral.com/pickaxe/ext_ruby.html

inline do |builder|
  builder.c "
    static VALUE some_method(VALUE s) {
      int s_len = RARRAY(s)->len;
      int result = 0;

      VALUE *s_arr = RARRAY(s)->ptr;

      for(i = 0; i < s_len; i++) {
        result += NUM2INT(s_arr[i]); // example of reference
      }

      return INT2NUM(result); // convert C int back into ruby Numeric 
    }"
end

然后在Ruby中你可以只值传递给它这样的:

Then in ruby you can just pass values to it like:

object.some_method([1,2,3,4])

希望这有助于你出去。

Hope this helps you out.

这篇关于如何红宝石数组转换为C数组了RubyInline?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆