红宝石传递数组值成C数组 [英] Passing ruby array values into a C array

查看:124
本文介绍了红宝石传递数组值成C数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图让在C红宝石独立FFT扩展的基础上的这个配方

I'm trying to make a standalone FFT extension for ruby in C, based on this recipe

我已经注意到通过红宝石和C之间的不同值的几种方法。但是即时通讯相当新的Ruby和C和不能工作如何从一个值Ruby对象数组复制到C数组。

I've noted several methods for passing different values between ruby and c. However im fairly new to both ruby and C and can't work out how to copy an array from a VALUE ruby object into a C array.

编译错误:
SimpleFFT.c:47:错误:下标值既不是数组,也不指针

The compilation error: SimpleFFT.c:47: error: subscripted value is neither array nor pointer

而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'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;
}

在此先感谢:)

推荐答案

您不能下标 inputArr ,因为它是一个而不是C数组。也就是说,这是一个标量类型。要访问一个特定的索引,使用

You can't subscript inputArr because it's a VALUE rather than a C array. Ie, it's a scalar type. To access a particular index, use

rb_ary_entry(inputArr, i)

顺便说一句,你可能想先验证它是一个数组:

As an aside, you might want to verify first that it's an array:

Check_Type(rarray, T_ARRAY);

这篇关于红宝石传递数组值成C数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆