What is the best way to return a string to the SWIG python interface?

c++, memory-management, python, string, swig

Solution

SWIG creates wrapper code to convert between C++ `std::string` and Python strings, if you include the typemaps defined in `std_string.i`.

Problem

What is a thread-safe and memory-leak-free way to return a string from C++ to the SWIG python interface? SWIG will automatically copy the contents of a `char *` return value into a python string. This SWIG guide gives the example: ``` char *__str__() { static char temp[256]; /* WRITE STUFF TO STRING */ return &temp[0]; } ``` 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. Returning a newly allocated string would create a memory leak, since SWIG would not know to free it. 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.

Original source