In article <d4cf71b0050127093664c9bf7b / mail.gmail.com>, Lyle Johnson wrote: >On Fri, 28 Jan 2005 01:56:24 +0900, Asbjøòn Reglund Thorsen ><asbjoert / ifi.uio.no> wrote: > >> I am quite new to extending Ruby, and I have read the README.EXT. >> I am wondering how to translate (from the code below): >> "PyList_SetItem($result, i, PyFloat_FromDouble((double) p(i+1)));" >> Into Extending Ruby syntax. > >The (roughly) equivalent code in a Ruby extension would be: > > $result = rb_ary_new2(size); > for (int i = 0; i < size; i++) > rb_ary_store($result, i, rb_float_new((double) p(i+1))); > >Note that in Ruby you construct an Array instance with a certain >initial size by calling rb_ary_new2(size), and then you set the array >items by calling rb_ary_store(). Also, the function for constructing a >Ruby Float object from a C double is rb_float_new(). As an alternative to rb_ary_store(), you can access the buffer underlying the Array directly: $result = rb_ary_new2(size); for (int i = 0; i < size; ++i) RARRAY($result)->ptr[i] = rb_float_new((double) p(i+1))); The latter is faster since it doesn't have to check things like - 'Do we need to increase the buffer size' - 'Is the buffer shared with another Array' - 'Is the Array frozen' ...etc.