# Creating Ruby objects from C

**URL:** <https://www.ruby-forum.com/t/creating-ruby-objects-from-c/88446>\
**Category:** Ruby\
**Created:** [March 11, 2007, 6:11am UTC](https://www.ruby-forum.com/t/creating-ruby-objects-from-c/88446 "2007-03-11T06:11:55Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![markcasio](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/m/e9bcb4/32.png) [@markcasio](https://www.ruby-forum.com/u/markcasio)\
**Post date:** [March 11, 2007, 6:11am UTC](https://www.ruby-forum.com/t/creating-ruby-objects-from-c/88446/1 "2007-03-11T06:11:55Z")

</div>

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);

---

<div class="post-metadata">

**Author:** ![markcasio](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/m/e9bcb4/32.png) [@markcasio](https://www.ruby-forum.com/u/markcasio)\
**Post date:** [March 11, 2007, 6:25am UTC](https://www.ruby-forum.com/t/creating-ruby-objects-from-c/88446/2 "2007-03-11T06:25:56Z")

</div>

On Mar 10, 2007, at 11:11 PM, Mark V. wrote:

> 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.

---

<div class="post-metadata">

**Author:** ![markcasio](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/m/e9bcb4/32.png) [@markcasio](https://www.ruby-forum.com/u/markcasio)\
**Post date:** [March 11, 2007, 9:37pm UTC](https://www.ruby-forum.com/t/creating-ruby-objects-from-c/88446/3 "2007-03-11T21:37:53Z")

</div>

On Mar 10, 2007, at 9:11 PM, Mark V. wrote:

> 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\>
