How to access ruby โ€‹โ€‹array from my c extension?

I get 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 does rb_ivar_get not actually point to the PairCounter class?

+2
source share
2 answers

I'm sure you need to use the RARRAY_PTR macro on pairs to get into the base array; for example, the internal implementation of the # push array (for 1.9.2) is as follows:

 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; } 

if just sorts any needed resizing, and then RARRAY_PTR(ary)[idx] to access one slot in the array.

I have no official links to this, but hopefully it will be useful.

+2
source

Ruby arrays are accessed using rb_ functions โ€” not like regular C arrays.

Use rb_ary_entry

VALUE rb_ary_entry(VALUE self, long index")

Returns an array of self in the index element.

Reference:

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

See the list of common array functions in the "Commonly Used Methods" section.

+1
source

All Articles