# Detaching free function from String in C API

**URL:** <https://rubytalk.org/t/detaching-free-function-from-string-in-c-api/45561>\
**Category:** ruby-talk\
**Created:** [1 April 2008 11:50 UTC](https://rubytalk.org/t/detaching-free-function-from-string-in-c-api/45561 "2008-04-01T11:50:08Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![Alex\_Fenton](https://avatars.discourse-cdn.com/v4/letter/a/ecccb3/32.png) [@Alex\_Fenton](https://rubytalk.org/u/Alex_Fenton)\
**Post date:** [1 April 2008 11:50 UTC](https://rubytalk.org/t/detaching-free-function-from-string-in-c-api/45561/1 "2008-04-01T11:50:08Z")

</div>

Hi

In a C extension, you can unset the 'free' function that will be called when an object is garbage collected with something like:

RDATA(obj)-\>dfree = 0;

This is useful if you know that whatever C library you're interfacing to will take care of free-ing the C structure.

Is the same thing is possible with an in-built ruby String object, to set it so that the underlying char\* contents will not be freed when the String is GC'd?

thanks  
alex

---

<div class="post-metadata">

**Author:** ![Alex\_Fenton](https://avatars.discourse-cdn.com/v4/letter/a/ecccb3/32.png) [@Alex\_Fenton](https://rubytalk.org/u/Alex_Fenton)\
**Post date:** [1 April 2008 14:35 UTC](https://rubytalk.org/t/detaching-free-function-from-string-in-c-api/45561/2 "2008-04-01T14:35:15Z")

</div>

ts wrote:

> Alex Fenton wrote:
> 
> > Is the same thing is possible with an in-built ruby String object, to  
> > set it so that the underlying char\* contents will not be freed when the  
> > String is GC'd?
> 
> Look at mmap (in RAA), when you write
> 
> &nbsp;&nbsp;m = Mmap.new("aa")
> 
> the object in `m' is in reality a String object and mmap make in  
> sort that ruby will never free the char \* content, otherwise it  
> will crash.

Perfect, thanks. I will read the source and ponder

alex
