如何在使用ruby内置类时调用ruby扩展方法

时间:2014-08-25 17:16:53

标签: c ruby rspec nmatrix

要跟进a question I asked alreadykind of solved as far as I got the answer to my question,尽管事实上已经解决了一个问题:

使用Complex API时遇到的问题是它无法识别NMatrix API中的形状方法:

因此,当我在my compiled C extension上运行以下规范代码时:

  it "Creates a new FFTW.r2c object and takes an a 1D NMatrix as its argument" do
    n = NMatrix.new([4], [3.10, 1.73, 1.04, 2.83])

    r = FFTW.Z(n)
    i = FFTW.Z(FFTW.r2c_one(r))
    #expect(fftw).to eq(fftw)
  end

因为shape属于nmatrix类而存在错误。

 FFTW Creates a new FFTW.r2c object and takes an a 1D NMatrix as its argument
     Failure/Error: i = FFTW.Z(FFTW.r2c_one(r))
     NoMethodError:
       undefined method `shape' for NMatrix:Class
     # ./spec/fftw_spec.rb:26:in `r2c_one'
     # ./spec/fftw_spec.rb:26:in `block (2 levels) in <top (required)>'

从nmatrix类中调用Shape,这样我就可以理解为什么会发生这种情况,但不知道如何绕过它。

的结果
  it "Creates a new FFTW.r2c object and takes an a 1D NMatrix as its argument" do
    n = NMatrix.new([4], [3.10, 1.73, 1.04, 2.83])

    fftw = FFTW.Z(n)
    expect(fftw).to eq(fftw)
  end

/home/magpie/.rvm/rubies/ruby-2.1.2/bin/ruby -I/home/magpie/.rvm/gems/ruby-2.1.2/gems/rspec-core-3.0.4/lib:/home/magpie/.rvm/gems/ruby-2.1.2/gems/rspec-support-3.0.4/lib -S /home/magpie/.rvm/gems/ruby-2.1.2/gems/rspec-core-3.0.4/exe/rspec ./spec/fftw_spec.rb
./lib/fftw/fftw.so found!

FFTW
  creates an NMatrix object
  Fills dense with individual assignments
  Creates a new FFTW.r2c object and takes an a 1D NMatrix as its argument

Finished in 0.00091 seconds (files took 0.07199 seconds to load)
3 examples, 0 failures

1 个答案:

答案 0 :(得分:2)

我认为问题在于fftw.cpp中的这段代码

第51-56行:

static VALUE
fftw_shape(VALUE self)
{
  // shape is a ruby array, e.g. [2, 2] for a 2x2 matrix
  return rb_funcall(cNMatrix, rb_intern("shape"), 0);
}

您正尝试在此处调用NMatrix类的形状。 rb_funcall的作用如下:

rb_funcall(object_to_invoke_method, method_to_invoke, number_of_args, ...)

问题是你在第一个参数位置有cNMatrix,所以它试图将shape方法发送到NMatrix 而不是物体。所以你真的想在nmatrix对象上调用它,如:

static VALUE
fftw_shape(VALUE self, VALUE nmatrix)
{
  // shape is a ruby array, e.g. [2, 2] for a 2x2 matrix
  return rb_funcall(nmatrix, rb_intern("shape"), 0);
}

和第82行:

VALUE shape = fftw_shape(self, nmatrix);

这有帮助吗?我认为唯一的问题是你在课堂上打电话给shape,但可能会出现其他问题。