arr=Array.new(3)
arr[0]=5
arr[1]=3
arr[2]=2
These lines should call this function, https://github.com/ruby/ruby/blob/trunk/array.c#L568 according to this, http://www.ruby-doc.org/core-1.9.3/Array.html
So I have added couple of lines there to display the values of array. But i didn’t get the expected result.
else {
memfill(RARRAY_PTR(ary), len, val);
ARY_SET_LEN(ary, len);
int i;
int result;
result = 0;
VALUE *s_arr = RARRAY_PTR(ary);
for(i = 0; i < len; i++) {
result = LONG2NUM(s_arr[i]);
printf("r: %d\n",result);
}
}
I got the result like this:
arr=Array.new(3)
arr[0]=5
arr[1]=3
arr[2]=2
r: 9
r: 9
r: 9
Why is this result? Why 9?
I have followed these to solve it:
- How to convert ruby array to C array with RubyInline?
- https://github.com/ruby/ruby/blob/trunk/README.EXT#L131
- https://github.com/ruby/ruby/blob/trunk/include/ruby/ruby.h#L708
- https://github.com/ruby/ruby/blob/trunk/include/ruby/ruby.h#L731
Can anyone please help to display/printf the value of Ruby array in C?
This doesn’t make any sense:
LONG2NUMis used to convert a Clong intto a RubyVALUEthat holds a number;s_arr[i]is already aVALUEso you’re effectively doing things likeVALUE v = LONG2NUM((VALUE)5).LONG2NUMis defined inruby.has a wrapper for this:and if
vfits in aVALUEwithout converting it to a bignum, then you end up using this:So you’re basically doing a bunch of bit wrangling on a pointer and wondering why it always says
9; consider yourself lucky (or unlucky) that it doesn’t say segmentation fault.You want to convert a
VALUEwhich holds a number to a C integer. You probably want to useFIX2LONG:or
NUM2LONG:So something like this:
Note the switch to
%ldsince we’re usinglongs now and we always turn on all the picky compiler flags that complain about mismatchedprintfformats and arguments. Of course, this assumes that you are certain that the array contains numbers that will fit in a Clong.