Passing ruby ​​array values ​​to C array

I am trying to make a standalone FFT extension for ruby ​​in C based on this recipe

I noted several ways to pass different values ​​between ruby ​​and c. However, im is pretty new to both ruby ​​and C, and cannot decide how to copy the array from the Ruby VALUE object to C array.

Compilation error: SimpleFFT.c: 47: error: the indexed value is neither an array nor a pointer

And the code:

#include "ruby.h" #include "fft.c" // the c file I wish to wrap in ruby VALUE SimpleFFT = Qnil; void Init_simplefft(); VALUE method_rfft(VALUE self, VALUE anObject); void Init_simplefft() { SimpleFFT = rb_define_module("SimpleFFT"); rb_define_method(SimpleFFT, "rfft", method_rfft, 1); } VALUE method_rfft(VALUE self, VALUE inputArr) { int N = RARRAY_LEN(inputArr); // this works :) // the FFT function takes an array of real and imaginary paired values double (*x)[2] = malloc(2 * N * sizeof(double)); // and requires as an argument another such array (empty) for the transformed output double (*X)[2] = malloc(2 * N * sizeof(double)); for(i=0; i<N; i++) { x[i][0]=NUM2DBL(inputArr[i]); // ***THIS LINE CAUSES THE ERROR*** x[i][1]=0; // setting all the imaginary values to zero for simplicity } fft(N, x, X); // the target function call // this bit should work in principle, dunno if it optimal VALUE outputArr = rb_ary_new(); for(i=0; i<N; i++){ rb_ary_push(outputArr, DBL2NUM(X[i][0])); } free(x); free(X); return outputArr; } 

Thank you in advance:)

+4
source share
2 answers

You cannot index inputArr because it is VALUE , not an array of C. That is, it is a scalar type. To access a specific index, use

 rb_ary_entry(inputArr, i) 

As an aside, you can first check that it is an array:

 Check_Type(rarray, T_ARRAY); 
+4
source

Looks like the answer to the question (and double checking my sources) helped me solve the answer.

replacements:

  rb_ary_push(outputArr, DBL2NUM(X[i][0])); 

with:

  x[i][0]=NUM2DBL(rb_ary_pop(inputArr)); 

seemed to do the trick :)

I still wonder if this is the most efficient way to do something, but it works.

+2
source

Source: https://habr.com/ru/post/1333251/


All Articles