Charles Mills
5/8/2005 4:37:00 AM
Ernest Ellingson wrote:
> I'm trying to do something real simple find the sin of an angle in an
> extension. I'm sure you'll recognize the following code as a
variation
> of the example in Pick Axe 2. I've read README.EXT. Looked at
Math.c
> been all over the web and I can't seem to figure out the correct way
to
> do this. Can someone give me a clue?
>
> Ernie
> #include "ruby.h"
> static int id_push;
This should be (int won't work on most/all 64 bit systems):
static ID id_push;
> static VALUE t_init(VALUE self)
> {
> VALUE arr;
> arr=rb_ary_new();
> rb_iv_set(self, "@arr", arr);
> return self;
> }
> static VALUE t_add(VALUE self, VALUE obj)
> {
> VALUE arr;
> VALUE si;
> arr=rb_iv_get(self, "@arr");
> si=sin(obj);
Read the man page for sin. Basically obj is a reference to a Ruby
Object not a double, so you need to go from a Ruby object to a double
here. Best way is
obj = rb_Float(obj);
- or -
obj = rb_convert_type(obj, T_FLOAT, "Float", "to_f");
then you can get treat obj as a T_FLOAT and cast it to a struct RFloat*
and get the value like so:
double sin_of_obj = sin(RFLOAT(obj)->value);
Finally you can create a new float from the result of sin() using
rb_float_new(sin_of_obj).
> rb_funcall(arr, id_push,1,si);
> return arr;
> }
>
> VALUE cTest;
> void Init_junk()
> {
> cTest=rb_define_class("Junk", rb_cObject);
> rb_define_method(cTest, "initialize",t_init,0);
> rb_define_method(cTest, "add", t_add,1);
> Init_Math();
> id_push = rb_intern("push");
> }
> after compiling
>
> require 'junk'
> a=Junk.new
> a.add(0.75)
> puts a => false;
I think all of the errors in your code would be caught be compiler
warnings, perhaps use -Wall / -W.
-Charlie