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.
SWIG creates wrapper code to convert between C++ std::string
and Python strings, if you include the typemaps defined in std_string.i
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With