From: Eric Wong Date: 2011-02-05T05:07:55+09:00 Subject: Re: Does RSTRING_PTR() return a '\0' terminated C? I単aki Baz Castillo wrote: > Hi, in a Ruby C extension I need to get a '\0' terminated string given > a Ruby string. I'm just interesed in Ruby 1.9. > > I'm testing that RSTRING_PTR(str) does returns a '\0' terminated > string, ot it seems so, but I'm not sure. Source code says: > > #define RSTRING_PTR(str) \ > (!(RBASIC(str)->flags & RSTRING_NOEMBED) ? \ > RSTRING(str)->as.ary : \ > RSTRING(str)->as.heap.ptr) > > Honestly, no idea about what it does :) It's one of my favorite things about Ruby 1.9: small strings (3 words - 1 byte) are embedded directly inside the object to avoid malloc() overhead. RSTRING_PTR() checks for the embed flag, and it'll return the embedded C string, otherwise it'll return the pointer allocated from malloc(). The same thing is done with RArray and RStruct, looking at the structure definitions will be useful. > So, can somebody ensure me that RSTRING_PTR() returns a pointer to C > char finished with '\0'? It's always '\0'-terminated in Ruby[1], it makes life much easier for interacting with existing C functions that assume C strings (e.g. *printf("%s"), open(), rename(), unlink(), etc...) [1] - unless there's a bug somewhere, or somebody hell bent on using the extra byte :) -- Eric Wong