How to convert a Ruby array to a C array with RubyInline?

I have a function that compares 2 char strings to char. I need it to work much faster than in Ruby, so I used RubyInline to rewrite the function in C. This increased the speed by about 100 times. The function is as follows:

  require 'inline'

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

however I need to compare unicode strings. So I decided to use unpack ("U *") and compare arrays of integers. I can’t understand from the meager RubyInline documentation how to pass ruby ​​arrays to a function and how to convert them to C. arrays Any help is appreciated!

+5
source share
2 answers

, Ruby 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 ​​ , :

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

, .

+9

, , Ruby 1.8.6 1.9.1:

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

, :)

+4

All Articles