creating Ruby objects from C

M

Mark Volkmann

The following snippet of C code shows my attempt to create a Ruby
string object by invoking the "new" method on the Ruby String class.
I know it would be easier to do this using the rb_str_new or
rb_str_new2 functions. However, I'm trying to understand how to
create arbitrary Ruby objects from C using the "new" method. Can you
spot what's wrong with this code?

ID class_id = rb_intern("String");
VALUE stringClass = rb_const_get(rb_cClass, class_id); // wrong
1st parameter?

ID method_id = rb_intern("new");
VALUE s1 = rb_funcall(stringClass, method_id, 1, "test");
printf("s1 = %s!\n", RSTRING(s1)->ptr);
 
M

Mark Volkmann

The following snippet of C code shows my attempt to create a Ruby
string object by invoking the "new" method on the Ruby String
class. I know it would be easier to do this using the rb_str_new or
rb_str_new2 functions. However, I'm trying to understand how to
create arbitrary Ruby objects from C using the "new" method. Can
you spot what's wrong with this code?

ID class_id = rb_intern("String");
VALUE stringClass = rb_const_get(rb_cClass, class_id); // wrong
1st parameter?

ID method_id = rb_intern("new");
VALUE s1 = rb_funcall(stringClass, method_id, 1, "test");
printf("s1 = %s!\n", RSTRING(s1)->ptr);

I think I found the answer. Using rb_class_new_instance works and is
much simpler that what I was attempting.
 
R

Ryan Davis

The following snippet of C code shows my attempt to create a Ruby
string object by invoking the "new" method on the Ruby String
class. I know it would be easier to do this using the rb_str_new or
rb_str_new2 functions. However, I'm trying to understand how to
create arbitrary Ruby objects from C using the "new" method. Can
you spot what's wrong with this code?

require 'rubygems'
require 'inline'

class X
def initialize
puts "blah"
end
end

class Y
inline do |builder|
builder.c '
VALUE blah() {
return rb_funcall(rb_path2class("X"), rb_intern("new"), 0);
}'
end
end

p Y.new.blah

# % ./blah.rb
# blah
# #<X:0x1090ec4>
 

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
473,995
Messages
2,570,226
Members
46,815
Latest member
treekmostly22

Latest Threads

Top