2010-12-24 19 views
4

我試圖讓在C紅寶石獨立FFT擴展,基於this recipe傳遞紅寶石數組值成C數組

我已經注意到通過紅寶石和C之間的不同值的幾種方法。然而,即時通訊相當新的紅寶石和C,並不能解決如何將數組從一個VALUE ruby​​對象複製到C數組。

的編譯錯誤: SimpleFFT.c:47:錯誤:下標值既不是數組,也不指針

,代碼:

#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's 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; 
} 

感謝提前:)

回答

4

你可以't下標inputArr,因爲它是VALUE而不是C數組。也就是說,這是一種標量類型。要訪問一個特定的索引,使用

rb_ary_entry(inputArr, i) 

順便說一句,你可能想先確認它是一個數組:

Check_Type(rarray, T_ARRAY); 
+0

感謝您的提示:)。我沒有清醒地回答自己,哎呀!訪問數組條目是否有任何原因可能比彈出數值更好或更差? – Nat 2010-12-24 02:24:08

2

貌似回答這個問題(和雙重檢查我的消息來源)幫我找出答案。

更換:

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

有:

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

似乎這樣的伎倆:)

我仍然不知道這是做事情的最有效的方式,但有用。