简体   繁体   English

如何从c扩展名访问ruby数组?

[英]How do I access a ruby array from my c extension?

I'm getting this error 我收到这个错误

ev.c:11: error: subscripted value is neither array nor pointer

for this line 对于这条线

printf("%d\n", pairs[0][0]);

In this code 在这段代码中

static VALUE EV;
static VALUE PairCounter;

static VALUE 
sort_pairs_2(VALUE self) {
    VALUE pairs;

    pairs = rb_ivar_get(self, rb_intern("pairs"));
    printf("%d\n", pairs[0][0]);
  return Qnil;
}

void Init_ev() {
    rb_eval_string("require './lib/ev/pair_counter'");
    VALUE PairCounter = rb_path2class("EV::PairCounter");
    rb_define_method(PairCounter, "sort_pairs_2", sort_pairs_2, 0);
}

Am I using self incorrectly, and rb_ivar_get is not actually pointing to the PairCounter class? 我是否使用了不正确的self,并且rb_ivar_get实际上没有指向PairCounter类?

I'm pretty sure you need to use the RARRAY_PTR macro on pairs to get at the underlying array; 我很确定您需要pairs使用RARRAY_PTR宏才能到达底层数组; for example, the internal implementation of Array#push (for 1.9.2) looks like this: 例如,Array#push(对于1.9.2)的内部实现如下所示:

static VALUE
rb_ary_push_1(VALUE ary, VALUE item)
{
    long idx = RARRAY_LEN(ary);

    if (idx >= ARY_CAPA(ary)) {
        ary_double_capa(ary, idx); 
    }
    RARRAY_PTR(ary)[idx] = item;
    ARY_SET_LEN(ary, idx + 1);   
    return ary;
}

The if just sorts out any necessary resizing, then there's RARRAY_PTR(ary)[idx] for accessing a single slot in the array. if只是整理出所有必要的调整大小,则可以使用RARRAY_PTR(ary)[idx]访问数组中的单个插槽。

I don't have any official references to back this up but hopefully this will be of some use. 我没有任何官方参考来支持此操作,但希望这会有所帮助。

Ruby arrays are accessed with rb_ functions - not like normal C arrays. Ruby数组是使用rb_函数访问的-与普通的C数组不同。

Use rb_ary_entry 使用rb_ary_entry

VALUE rb_ary_entry(VALUE self, long index")

Returns array self 's element at index . index处返回数组self的元素。

Reference: 参考:

http://ruby-doc.org/docs/ProgrammingRuby/html/ext_ruby.html http://ruby-doc.org/docs/ProgrammingRuby/html/ext_ruby.html

See a list of common Array functions under "Commonly Used Methods" . 请参阅“常用方法”下的常见数组函数列表。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM