Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 216
Matt Avatar asked Jul 07 '14 14:07

Matt


1 Answers

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

like image 152
Oliver Avatar answered Sep 23 '22 16:09

Oliver