I am new at programming ruby with C. I am trying to pass in a value from
a test ruby program to my C class and trying to print it out. But when i
print it out i am getting the wrong number printerd out.
Here is what i am trying to do.
Here is the ruby test file
class TestTest < Test::Unit::TestCase
def test_test
k = PKey.new(‘4’)
assert_equal(Object, PKey.superclass)
assert_equal(PKey, k.class)
trtying = k.bit(5)
end
end
Here is the C file
static VALUE t_bit(VALUE self, VALUE obj)
{
VALUE n;
n = NUM2INT(obj);
printf("Fun %d", INT2NUM(n));
return Qnil;
By putting the variable ‘n’ through the INT2NUM macro as you pass it
into printf you’re re-converting it back into a Ruby VALUE which is
not what you want to do. It will give you unpredictable (or at least
more-difficult-to-predict ) results…
Assuming you just want to print the value of ‘obj’ as an integer, you
should probably declare ‘n’ as an integer instead of as a VALUE, and
use the NUM2INT (as you have) to convert the Ruby VALUE ‘obj’ into a
plain int. Then you can pass it straight into printf (as you would
with any other int) … no need for INT2NUM there.
Your question has already been answered. Alternatively, use inline to
learn without all the hassle (no makefile, no builds, no type
conversions, no time wasted). Just try out what you want to do
straight up in ruby with inlined C, and then go look at what the C
code is producing:
#!/usr/local/bin/ruby
require ‘rubygems’
require ‘inline’
class PKey
inline do |builder|
builder.c <<-EOM
static void bit(int n) {
printf(“Fun %d\n”, n);
}
EOM
end
end