Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/59.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何使用RubyLine将ruby数组转换为C数组?_C_Ruby - Fatal编程技术网

如何使用RubyLine将ruby数组转换为C数组?

如何使用RubyLine将ruby数组转换为C数组?,c,ruby,C,Ruby,我有一个函数,它逐字符比较两个字符串。我需要它运行得比Ruby快得多,所以我用RubyLine在C中重写了这个函数。它确实提高了大约100倍的速度。函数如下所示: require 'inline' inline do |builder| builder.c " static int distance(char *s, char *t){ ... }" end 但是,我需要比较unicode字符串。所以我决定使用unpack(“U*”

我有一个函数,它逐字符比较两个字符串。我需要它运行得比Ruby快得多,所以我用RubyLine在C中重写了这个函数。它确实提高了大约100倍的速度。函数如下所示:

  require 'inline'

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

但是,我需要比较unicode字符串。所以我决定使用unpack(“U*”)来比较整数数组。我无法从RubyLine的少量文档中了解如何将ruby数组传递到函数中,以及如何将它们转换为C数组。感谢您的帮助

这篇文章详细介绍了如何从C访问Ruby对象:


希望这对您有所帮助。

根据以上答案中的代码,以下是适用于Ruby 1.8.6和1.9.1的代码:

inline do|builder|
建筑商c“
静态值某些_方法(值s){
int s_len=RARRAY_len(s);
int结果=0;
int i=0;
值*s_arr=RARRAY_PTR(s);
对于(i=0;i

希望这也能有所帮助:)

谢谢Corban,它看起来正是我需要的!没问题,让我知道结果如何。我很想看到你的实现。下面是damerau_levenshtein distance的代码:对于ruby 1.8.7来说,它就像一个魔咒,但是被ruby 1.9.1绊住了。我通过thnetosThanks thnetos的帮助更新了ruby 1.9.1,它确实解决了问题,我更新了github gist示例
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
object.some_method([1,2,3,4])
inline do |builder|
  builder.c "
    static VALUE some_method(VALUE s) {
      int s_len = RARRAY_LEN(s);
      int result = 0;
      int i = 0;

      VALUE *s_arr = RARRAY_PTR(s);

      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