Accessing Ruby arrays from C

I had assumed that these 2 methods of accessing a Ruby array element from C are identical:

	 anedge = RARRAY_PTR(edges)[eindex];


	anedge = rb_ary_entry(edges, eindex);

But I’m beginning to think the former has some instability - eg I see random stuff in some array elements, sometimes. Not easy to repro, but does occur.

Is the former obviously unsafe?

I can only quote the documentation. Although, there is no explanation given for the following statement.

Don’t touch pointers directly

In MRI (include/ruby/ruby.h), some macros to acquire pointers to the internal data structures are supported such as RARRAY_PTR(), RSTRUCT_PTR() and so on.

DO NOT USE THESE MACROS and instead use the corresponding C-APIs such as rb_ary_aref(), rb_ary_store() and so on.

1 Like

[I dont think they’re different - I was chasing a red herring :frowning: ]

Also the “DO NOT USE…” is just to encourage using immutable APIs rather than behaviour.

I just had a look at Ruby source code and rb_ary_entry() just calls rb_ary_entry_internal() which check the array bounds before doing RARRAY_PTR(edges)[eindex]

So definitely the same but without bounds checking.

1 Like