我有一个函数比较2个字符串char by char.我需要它比在Ruby中运行得快得多,所以我使用RubyInline来重写C中的函数.它确实将速度提高了大约100倍.该函数如下所示:
require 'inline'
inline do |builder|
builder.c "
static int distance(char *s, char *t){
...
}"
end
Run Code Online (Sandbox Code Playgroud)
但是我需要比较unicode字符串.所以我决定使用unpack("U*")并比较整数数组.我无法从一个简短的文档中找出RubyInline如何将ruby数组传递给函数以及如何将它们转换为C数组.任何帮助表示赞赏!
这有关如何从C访问Ruby对象的一个很好的概述: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
Run Code Online (Sandbox Code Playgroud)
然后在ruby中,您可以将值传递给它,如:
object.some_method([1,2,3,4])
Run Code Online (Sandbox Code Playgroud)
希望这可以帮助你.
| 归档时间: |
|
| 查看次数: |
1998 次 |
| 最近记录: |