Declaring Class Method with RubyInline

2019-08-30 23:16发布

问题:

I have the following lines of code in my test_func.rb

require 'inline'

class TestFunc
  inline do |builder|
    builder.c '
      int testfunc() {
        return 0;
      }'
  end
end

I am able to call the function only from an object and not class.

I can call it as,

obj = TestFunc.new
obj.testfunc()

But how should i declare so that i can call as,

TestFunc.testfunc()

回答1:

Use Inline::C#c_singleton instead of Inline::C#c:

require 'inline'

class TestFunc
  inline do |builder|
    builder.c_singleton '
    int testfunc() {
      return 0;
    }'
  end

end

TestFunc.testfunc() # => 0

According to the documentation:

c_singleton: Same as c, but adds a class function.