default values

  • Thread starter Elias Athanasopoulos
  • Start date
E

Elias Athanasopoulos

Hello!

Is there a fast way to create prototypes such:

def foo(bar=0)
...
end

in a Ruby extension? Or I have to use:

rb_define_method(foo, "...", func, -1);

and parse the variables using rb_scan_args()?

Regards,
 
T

ts

E> in a Ruby extension? Or I have to use:
E> rb_define_method(foo, "...", func, -1);
E> and parse the variables using rb_scan_args()?

Yes, you have to do this


Guy Decoux
 
J

Joel VanderWerf

Elias said:
Hello!

Is there a fast way to create prototypes such:

def foo(bar=0)
...
end

in a Ruby extension? Or I have to use:

rb_define_method(foo, "...", func, -1);

and parse the variables using rb_scan_args()?

If you don't mind taking a code generation approach, there is a way to
make rb_define_method and rb_scan_args a bit more palatable. My cgen
library on RAA gives you ruby methods for generating a ruby extension in
C. A simple example:

===============
require 'cgen/cshadow'

class MyComplex2 < Numeric
include CShadow

shadow_attr_accessor :re => "double re", :im => "double im"

def initialize re, im
self.re = re
self.im = im
end

define_c_method:)abs) {
include "<math.h>"
returns "rb_float_new(sqrt(pow(shadow->re, 2) + pow(shadow->im, 2)))"
}

define_c_method:)scale!) {
c_array_args {
optional :factor
default :factor => "INT2NUM(10)"
typecheck :factor => Numeric
}
body %{
shadow->re *= NUM2DBL(factor);
shadow->im *= NUM2DBL(factor);
}
returns "self"
}
end

require 'ftools'
dir = File.join("tmp", RUBY_VERSION)
File.mkpath dir
Dir.chdir dir do
MyComplex2.commit
end

MyComplex2.commit # compiles and load the library

z = MyComplex2.new 5, 1.3
puts z.abs # ==> 5.1662365412358
z.scale! 3.0 # float
p [z.re, z.im] # ==> [15.0, 3.9]
z.scale! 3 # int
p [z.re, z.im] # ==> [45.0, 11.7]
z.scale! # use default value
p [z.re, z.im] # ==> [450.0, 117]
===============

CShadow also takes care of load/dump/mark/free/alloc/new as well as
accessors with type conversion/checking.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,142
Messages
2,570,818
Members
47,362
Latest member
eitamoro

Latest Threads

Top