Subject:
Re: [ruby-ffi] Ruby Array Pointer
From:
Chuck Remes
Date:
6/8/10 9:29 PM
To:
ruby-ffi@googlegroups.com


On Jun 8, 2010, at 5:25 PM, v01d wrote:

> Hi,
> is it possible to pass a C function the data pointer to a Ruby array?
> I have a Matrix class, and I wish to write a "to_a" method which will
> produce an array of arrays. I've tried several ways and tested the
> performance but it seems really slow, and I think it would be better
> to just attach a C function that would take the pointer to the
> destination array and the pointer to the input data contained in the
> matrix (this second part is no problem).
> Is this possible? Or I have to resort to writing a C function that
> accesses the array using RARRAY_PTR and such?

What you want to do is possible, but it is outside the capability of FFI. You want to create a regular C extension. Be warned that it will not work on all Ruby runtimes since few (outside of MRI) provide the RARRY_PTR macro.

To do it within the boundaries of FFI, you will need to copy the data from the Ruby array to a native memory chunk allocated via malloc. This memory can then be handed off to your C functions for manipulation. To expose it to Ruby again, the data will need to be copied back.

cr