[CExt] C array to Ruby Array?
-
Say you have a C array,
int carr[10];
ordouble carr[10];
.
Is there a single method to convert the C array to a Ruby array?Or does one have to create a Ruby array, iterate the C array and populate one value at a time?
-
Ruby has its wonderful numbers (integers when possible, floats as needed) but they aren't C's much simpler (and faster) plain numbers. Cs numbers can be used directly by the CPU/FPU. Ruby's numbers are object instances.
-
I am writing a Ruby C Extension. What I tried to hint by [CExt].
TDB let me know I need to do the latter in order to convert C arrays to Ruby arrays.
-
Generally No, because the underlying representations are different. (eg Integer in Ruby is actually an integer times 4)
Doubles are the exception as the representation in C and Ruby are the same IEEE format.
So the values can simply be copied. However the container is another matter; in C, arrays are little more than syntactic sugar, in Ruby an Array is a real live object, so you're kinda out luck.
The best you could do would be something like:
extern double *reals extern int rcount; static VALUE method_getRealArray(VALUE rarray) { if (rcount < RARRAY_LEN(rarray)) { memcpy(RARRAY_PTR(rarray), reals, sizeof(double)* rcount); return Qtrue; } else { return Qfalse; } }
Advertisement