From: Charles Mills Date: 2004-07-20T03:35:46+09:00 Subject: Re: str_buf safety On Jul 19, 2004, at 11:25 AM, Charles Mills wrote: > Is it safe so set the length of a String Buffer like so: > { > VALUE str_buf; > long len = len_of_ext_data_source; > unsigned char *buf = ptr_to_ext_data_source; > > str_buf = rb_str_buf_new(len); > /* bug: Dangerous to set Ruby String fields directly? */ > MEMCPY(RSTRING(str_buf)->ptr, buf, unsigned char, len); > RSTRING(str_buf)->len = len; > return str_buf; > } > Where len is the length of some buffer and buf is a pointer to that > buffer. > -Charlie > I just realized this example suggests I should use: VALUE str = rb_str_new(buf, len); Unfortunately I cannot do that (without allocating 2 buffers) since I have a routine pack() which packs an object into a buffer. I was hoping I could do the following: { long len = pack_size(obj); VALUE str_buf = rb_str_buf_new(len); pack(obj, RSTRING(str_buf)->ptr, len); RSTRING(str_buf)->len = len; return str_buf; } I am sure something similar is done with the read() system call in io.c, ... I will look there. -Charlie