# Copying data into a String inside a C extension

**URL:** <https://www.ruby-forum.com/t/copying-data-into-a-string-inside-a-c-extension/125771>\
**Category:** Ruby\
**Created:** [January 11, 2008, 9:43pm UTC](https://www.ruby-forum.com/t/copying-data-into-a-string-inside-a-c-extension/125771 "2008-01-11T21:43:00Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![murfhy](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/m/d26b3c/32.png) [@murfhy](https://www.ruby-forum.com/u/murfhy)\
**Post date:** [January 11, 2008, 9:43pm UTC](https://www.ruby-forum.com/t/copying-data-into-a-string-inside-a-c-extension/125771/1 "2008-01-11T21:43:00Z")

</div>

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 \*/

(this is intended for Ruby 1.9)

buffer\_read is the function which writes data into the string’s buffer.

The RSTRING(str)-\>as.heap.len = length bit was stolen from the  
STR\_SET\_LEN  
macro in string.c, but this doesn’t seem available in ruby.h

What’s the proper way to do this sort of thing?

---

<div class="post-metadata">

**Author:** ![murfhy](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/m/d26b3c/32.png) [@murfhy](https://www.ruby-forum.com/u/murfhy)\
**Post date:** [January 12, 2008, 3:26am UTC](https://www.ruby-forum.com/t/copying-data-into-a-string-inside-a-c-extension/125771/2 "2008-01-12T03:26:51Z")

</div>

On Jan 11, 2008 12:40 PM, Tony A. [removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid) wrote:

> 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
