Redefining rb_str_init()

D

Daniel Berger

Hi all,

I'm just messing around with a custom String class, so I did this to
string.c:

static VALUE rb_str_init(int argc, VALUE* argv, VALUE v_str){
VALUE v_orig;

rb_scan_args(argc, argv, "01", &v_orig);

if(RTEST(v_orig))
rb_str_replace(v_str, v_orig);

printf("Hello!\n");

return v_str;
}

I rebuilt Ruby and installed it without issue. But, the "Hello" only
prints if you use the long form of the constructor:

s1 = String.new('test') # "Hello!"
s2 = "test" # Nothing printed

What do I need to change to make the constructor shortcut work as
expected?

Thanks,

Dan
 
Y

Yukihiro Matsumoto

Hi,

In message "Re: Redefining rb_str_init()"

|What do I need to change to make the constructor shortcut work as
|expected?

I don't think it's a good idea to invoke function for every string
allocation. But if you really want to do, modify str_alloc() in
string.c.

In general, #initialize is not called for literals.

matz.
 
D

Daniel Berger

Yukihiro said:
Hi,

In message "Re: Redefining rb_str_init()"

|What do I need to change to make the constructor shortcut work as
|expected?

I don't think it's a good idea to invoke function for every string
allocation. But if you really want to do, modify str_alloc() in
string.c.

Well, I'm just tinkering around for now. However, I did realize
something interesting. I put a printf in the str_alloc() function as
you mentioned and ran an empty Ruby program. Even an empty Ruby program
appears to invoke the str_alloc function 107 times!

I take it there's a bunch of setup happening within the interpreter that
makes a lot of calls to str_alloc() before the interpeter ever runs?
That, or I've messed something up.
In general, #initialize is not called for literals.

matz.

Good to know, thanks,

- Dan
 
J

Joel VanderWerf

Daniel Berger wrote:
...
I take it there's a bunch of setup happening within the interpreter that
makes a lot of calls to str_alloc() before the interpeter ever runs?
That, or I've messed something up.

Strings like this...

$ RUBYLIB='' RUBYOPT='' ruby -e 'a=[];ObjectSpace.each_object(String)
{|s| a<<s}; puts a'
a=[];ObjectSpace.each_object(String) {|s| a<<s}; puts a
 

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

No members online now.

Forum statistics

Threads
474,201
Messages
2,571,048
Members
47,647
Latest member
NelleMacy9

Latest Threads

Top