title: What is the best way to return a string to the SWIG python interface?
body: <p>What is a thread-safe and memory-leak-free way to return a string from C++ to the SWIG python interface?</p>
  
  <p>SWIG will automatically copy the contents of a <code>char *</code> return value into a python string. <a href="http://www.swig.org/Doc1.3/SWIGPlus.html#SWIGPlus_class_extension" rel="noreferrer">This SWIG guide</a> gives the example:</p>
  
  <pre><code>char *__str__() {
      static char temp[256];
      /* WRITE STUFF TO STRING */
      return &amp;temp[0];
  }
  </code></pre>
  
  <p>Their example uses a static string as a return value, but if my C++ program has multiple threads, they could easily overwrite each other's strings.</p>
  
  <p>Returning a newly allocated string would create a memory leak, since SWIG would not know to free it.</p>
  
  <p>The only thing I can think of is to register and return a pointer to an actual python string object (that way the python garbage collector would take care of it), but I am not sure how to go about that and am wondering if there is an easier way.</p>