From: "Carlo E. Prelz" Date: 2013-04-09T05:06:11+09:00 Subject: Re: Mapping string data ptr to buffer in ffi 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); (there is also int l=RSTRING_LEN(v); that returns the length of the string (strings in Ruby are not NULL-terminated)). 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. When you embrace a garbage-collected language you have VAST advantages. They come with their fair share of disadvantages, like a performance hit, and having to forget about playing with pointers. Then, as I already wrote, I believe it is possible to derive from the stuff in string.c an immutable string object where content points to some underlying storage, but it is certainly not trivial. What I am reasonably certain is a dead end is transmitting memory pointers to the Ruby environment. You can, of course, obtain the value of the memory location, but there's little you will want to do with it. Carlo -- * Se la Strada e la sua Virtu' non fossero state messe da parte, * K * Carlo E. Prelz - fluido@fluido.as che bisogno ci sarebbe * di parlare tanto di amore e di rettitudine? (Chuang-Tzu)