[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; } }
Hello! It looks like you're interested in this conversation, but you don't have an account yet.
Getting fed up of having to scroll through the same posts each visit? When you register for an account, you'll always come back to exactly where you were before, and choose to be notified of new replies (either via email, or push notification). You'll also be able to save bookmarks and upvote posts to show your appreciation to other community members.
With your input, this post could be even better π
Register LoginAdvertisement