gpt4 book ai didi

c - 将 ruby​​ 数组值传递到 C 数组

转载 作者:数据小太阳 更新时间:2023-10-29 07:29:27 25 4
gpt4 key购买 nike

我正在尝试基于 this recipe 在 C 中为 ruby​​ 制作一个独立的 FFT 扩展

我注意到了几种在 ruby​​ 和 c 之间传递不同值的方法。然而,我对 ruby​​ 和 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;
}

提前致谢:)

最佳答案

您不能为 inputArr 添加下标,因为它是一个 VALUE 而不是一个 C 数组。即,它是标量类型。要访问特定索引,请使用

rb_ary_entry(inputArr, i)

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

Check_Type(rarray, T_ARRAY);

关于c - 将 ruby​​ 数组值传递到 C 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4523597/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com