From: Adam Bozanich Date: 2008-01-12T11:26:21+09:00 Subject: Re: Copying data into a String inside a C extension ------=_Part_3861_23137010.1200104785600 Content-Type: text/plain; charset=ISO-8859-1 Content-Transfer-Encoding: 7bit Content-Disposition: inline On Jan 11, 2008 12:40 PM, Tony Arcieri wrote: > I'm extracting data from a function in C which accepts a pointer to the > string to dump the data into. > > I know the length beforehand, so what I need to do is create a new String > of > a given length and pass the pointer to the String's buffer to function > which > writes into it. > > Currently I'm doing this: > > str = rb_str_buf_new(length); > buffer_read(buf, RSTRING_PTR(str), length); > RSTRING(str)->as.heap.len = length; /* <-- something tells me this is bad > */ > RSTRING_PTR(str)[length] = '\0'; /* sentinel */ > Hi Tony, You can pass the null pointer to rb_str_new() like so: VALUE str = rb_str_new(0,length); if you follow the call flow, it'll end up in str_new(), which allocates space for length bytes but only copies the data in if ptr is not null. -Adam ------=_Part_3861_23137010.1200104785600--