Question on StringValuePtr, rb_str_dup

Hi all,

I'm having a hard time preserving a string. Essentially, what's
happening is that even though I'm dup'ing the original string, after I
pass it a C function that modifies the receiver, both the original
string *and* the dup appear to be affected.

Here's a generic example of what I mean:

static VALUE foo(VALUE klass, VALUE rstring_orig){
   VALUE rstring;
   char* string;

   rstring = rb_str_dup(rstring_orig);
   string = StringValuePtr(rstring);

   c_func_that_modifies_receiver(string);

   return rb_str_new2(string);
}

string = "hello"
foo(string)
p string # modified, but shouldn't be.

In other words, even though I've dup'd the original string and have sent
the dup to the C function that modifies the receiver, the original
string is still being modified.

What am I doing wrong here?

Thanks.

Dan

Hi,

···

In message "Re: Question on StringValuePtr, rb_str_dup" on Wed, 14 Sep 2005 06:38:44 +0900, "Berger, Daniel" <Daniel.Berger@qwest.com> writes:

I'm having a hard time preserving a string. Essentially, what's
happening is that even though I'm dup'ing the original string, after I
pass it a C function that modifies the receiver, both the original
string *and* the dup appear to be affected.

Because plain duplication shares internal memory region. You have to
call rb_str_modify() before modifying a string.

              matz.

Hi,

At Wed, 14 Sep 2005 06:38:44 +0900,
Berger, Daniel wrote in [ruby-talk:156009]:

static VALUE foo(VALUE klass, VALUE rstring_orig){
   VALUE rstring;
   char* string;

   rstring = rb_str_dup(rstring_orig);

     rb_str_modify(rstring);

···

   string = StringValuePtr(rstring);

   c_func_that_modifies_receiver(string);

   return rb_str_new2(string);
}

--
Nobu Nakada