Strings in a Ruby 1.9 C extension?

Hi,

I'm wishing that the Ruby C API had a function like:

VALUE str = rb_str_prealloc(size_t len);

Why? So I could then do this:

char *c_ptr = RSTRING_PTR(str);
size_t rlen = some_other_c_lib_func(some_input_arg, str, len);

The idea is that I could then call a C function that would use the
preallocated buffer from the Ruby string and fill it fully or
partially. Then I would need something like:

rb_str_setlen(str, rlen);

The idea is that this function would set the actual string length so
long as rlen is less than or equal to the preallocated size.
Internally, rb_str_setlen(str, rlen) would double-check that rlen
doesn't exceed the allocated buffer size.

QUESTIONs:

Are there any existing C functions like this for Ruby 1.9 (MRI)? So
far it appears that I'm going to have to roll my own, borrowing code
from the RSTRING_LEN/RSTRING_PTR macros to handle cases where a
preallocation length was very small (<=RSTRING_EMBED_LEN_MAX).

Thanks,
Aaron out.

rb_str_buf_new(long capacity) is what you're looking for. The capacity argument need not include space for a null terminator, the function adds 1 to it for the terminator.

My typical approach is to look in intern.h and ruby.h for relevant function calls, and then dive into the source to figure out what function does what.

···

On Sep 9, 2011, at 1:07 PM, "Aaron D. Gifford" <astounding@gmail.com> wrote:

Hi,

I'm wishing that the Ruby C API had a function like:

VALUE str = rb_str_prealloc(size_t len);

Why? So I could then do this:

char *c_ptr = RSTRING_PTR(str);
size_t rlen = some_other_c_lib_func(some_input_arg, str, len);

The idea is that I could then call a C function that would use the
preallocated buffer from the Ruby string and fill it fully or
partially. Then I would need something like:

rb_str_setlen(str, rlen);

The idea is that this function would set the actual string length so
long as rlen is less than or equal to the preallocated size.
Internally, rb_str_setlen(str, rlen) would double-check that rlen
doesn't exceed the allocated buffer size.

QUESTIONs:

Are there any existing C functions like this for Ruby 1.9 (MRI)? So
far it appears that I'm going to have to roll my own, borrowing code
from the RSTRING_LEN/RSTRING_PTR macros to handle cases where a
preallocation length was very small (<=RSTRING_EMBED_LEN_MAX).

Thanks,
Aaron out.

Yeah, that's what I've been doing. I must have missed that as that's
exactly what I was looking for. Thank you.

Aaron out.

···

On Fri, Sep 9, 2011 at 11:32 AM, Michael Edgar <adgar@carboni.ca> wrote:

rb_str_buf_new(long capacity) is what you're looking for. The capacity argument need not include space for a null terminator, the function adds 1 to it for the terminator.

My typical approach is to look in intern.h and ruby.h for relevant function calls, and then dive into the source to figure out what function does what.