From: Jeremy Bopp Date: 2013-04-09T05:27:43+09:00 Subject: Re: Mapping string data ptr to buffer in ffi On 04/08/2013 03:06 PM, Carlo E. Prelz wrote: > Subject: Re: Mapping string data ptr to buffer in ffi > Date: mar 09 apr 13 04:31:39 +0900 > > Quoting Jeremy Bopp (jeremy@bopp.net): > >> I would be interested to hear about any solution in this vein as well. >> It seems to boil down to this: can the byte buffer that backs Ruby >> strings be exposed for direct use by C functions? If not, then this >> discussion can only move on to alternatives. If it can be done, how so? > The buffer can be accessed quite easily. If v is a VALUE that refers > to a String object, you can do > > char *p=RSTRING_PTR(v); Sadly, this doesn't appear to be made available via any functionality of FFI, so the OP would need to write at least a small amount of his own glue as a C extension or similarly extend FFI. From the earlier discussion, the hope is that such functionality already exists in FFI. The next question to answer is whether or not the GC will relocate that buffer behind the back of the C functions. If that might happen, the GC might need to be disabled during any operations that use the buffer with the C function. > What you can't do if you want to keep the Ruby > environment (and yourself) happy is change the size of that buffer, or > free the buffer, or other actions of this sort. If you want to > manipulate that string from C, you are free to allocate your own > buffers, and assume the responsibility to free them, or leak memory. In my case at least, all operations on the buffer would only change content within the existing buffer. The size of the string that owns the buffer would be unaffected. I think the OP has similar needs from the sound of it. -Jeremy