Ruby代码
require'mkmf'create_makefile("string_hack");
|
执行ruby extconf.rb,将产生一个Makefile,执行make,生成一个string_hack.so的链接库。扩展写完了,通过ruby调用:
Ruby代码
require'string_hack"t=Test.new(1..3).each{|i|t.test}
|
输出:
before concat: str:0x40098a40, str.aux.shared:0x3, str.ptr:str
after concat: str:0x40098a40, str.aux.shared:0x8, str.ptr:string
before concat: str:0x40098a2c, str.aux.shared:0x3, str.ptr:str
after concat: str:0x40098a2c, str.aux.shared:0x8, str.ptr:string
before concat: str:0x40098a18, str.aux.shared:0x3, str.ptr:str
after concat: str:0x40098a18, str.aux.shared:0x8, str.ptr:string
|
从结果可以看出,在str concat之前之后,str指向的位置没有改变,改变的仅仅是str中ptr指向的字符串的值,看看rb_str_cat2函数的实现就一目了然了:
cpp代码
VALUErb_str_cat(str,ptr,len)VALUEstr;
constchar*ptr;
longlen;
{
if(len<0){rb_raise(rb_eArgError,"negativestringsize(orsizetoobig)");
}
if(FL_TEST(str,STR_ASSOC))
{
rb_str_modify(str);
REALLOC_N(RSTRING(str)->ptr,char,RSTRING(str)->len+len);
memcpy(RSTRING(str)->ptr+RSTRING(str)->len,ptr,len);
RSTRING(str)->len+=len;
RSTRING(str)->ptr[RSTRING(str)->len]='"0';
/*sentinel*/
returnstr;
}
returnrb_str_buf_cat(str,ptr,len);
}
VALUErb_str_cat2(str,ptr)VALUEstr;
constchar*ptr;
{
returnrb_str_cat(str,ptr,strlen(ptr));
}
//string.c
|
|